Help with program

So I have to make a program that allows the user to enter bot positive and negative numbers and the program is suppose to calculate the sum of only the positive values while ignoring the negative values. Also it is to be a sentinel-controlled loop with a number ending the set of values.

Im at a complete loss any help would be appreciated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{

	int input, sentinel = 0, sum = 0;
	while (input != sentinel) //while input is not 0
	{
		cin >> input; //get input
		if (input > 0) //if input is positive
		{
			sum+= input; //add input to sum
		}
	}
	cout << sum; //output final sum
}
Last edited on
this is what I have and it doesn't ask the user to input integers when compiled

Last edited on
int userInput; instead of int userInput = 0;

Also to ignore the negative numbers you should replace if(userInput!=0) with
if(userInput>0)
Last edited on
Rather than not initialize userInput it might be better to give it some value you know will cause it to enter the loop (like 1 for instance.) An uninitialized variable may have any value, including the value 0 which would lead to the loop never being entered. Worse, it may be entered sometimes and not be entered at other times.

Or, maybe you want to use a loop that is better suited to this situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
    const int sentinel = 0;
    int sum = 0 ;
    int userInput ;

    do
    {
        cout << "Enter data (0 to exit): " ;
        cin >> userInput ;
        if ( userInput > 0 )
            sum += userInput ;

    } while ( userInput != sentinel );

    cout << "The sum of the positive numbers is " << sum << '\n' ;
}
Last edited on
Topic archived. No new replies allowed.