Display the sum and the count of the positive numbers in a loop.

Write a C++ program that will input only the positive numbers from the user in a loop.
If the user inputs the negative number then the loop will terminate.
Display the sum and the count of the positive numbers.

My try to solve the question but its all wrong and im lost.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
int i, counter = 0, sum = 0;
while(counter != 3)
{
cout << "Enter a number:";
cin >> i;
if( i > 0) sum += i;
else counter++;
cout << "Sum = " << sum;
cout<<" Count= "<< count;
}
return 0;
}


Sample Output:

Enter a number: 2
Enter a number: 4
Enter a number: 8
Enter a number: -2

Sum=14
Count=3
Last edited on
Maybe like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
while (true)
{
  cout << "Enter a number - negative to quit ";
  cin >> num;
  if (num > 0)
  {
    count++;
    sum += num;
  }
  else if (num < 0)
    break;
  // 0 will be ignored
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
int i = 0, counter = 0, sum = 0;
while(i > -1)
{
cout << "Enter a number:";
cin >> i;
    if( i > 0) {
        sum += i;
        counter++;
    }
}
cout << "Sum = " << sum;
cout << " Count= " << counter;

return 0;
}
Yess perfect, thanks both!
Topic archived. No new replies allowed.