# How to average positive inputs until a negative input is given

How can I accept and average positive numbers? When a negative number is entered, it should terminate the loop and display the average (excluding the negative number).

#include <iostream> using namespace std ; int main () { int x,counter=0,sum; float avg; while (x>0) { if(x<0) { sum+=x; counter++; continue; } else if (x>0) { cin>>x; sum+=x; counter ++; } } avg=(float)sum/counter; cout<<avg<<endl; return 0 ; }

## Answers

#include <iostream> using namespace std; int main() { int sum = 0, count = 0, input; // initialize all variables while (true) { // loop forever (until break is reached below) cin >> input; // get user input if (input < 0) break; // if it's negative, exit loop sum += input; // otherwise add it to the running sum count++; // increase the count by 1 } if (count > 0) cout << (double)sum / count; // if we have at least one number, display avg else cout << "No numbers to average" << endl; // else complain. return 0; }

Note that this will fail if the user provides bad input. If you need it to handle bad input, see here about cin types.

The implementation that you have immediately adds the input to your sum.

int main () { int x,counter=0,sum; float avg; while (x>0) { cin >> x; if (x>0) { sum+=x; counter ++; } } avg=(float)sum/counter; cout<<avg<<endl; return 0 ; }

This would allow you to check the input before adding to your total.

It is also important to mention to avoid dividing by zero if the user's first input is a negative number.

here is an improved version, that checks if loop exist without any positive integers entered to avoid divide by zero error

#include <iostream> using namespace std ; int main () { int x; float counter=0,sum; float avg; bool isPositive = true; while ( isPositive) { cin>>x; if(x>0) { sum+=x; counter ++; } else { isPositive = false; } } // if we divide by zero, an error will occur if(counter > 0) { avg=(float)(sum/counter); cout<<avg<<endl; } else cout << "Please enter positive numbers"; return 0 ; }