new at c++ having trouble with a for loop

#include <iostream>
using namespace std;


int main()
{
int sum=0;
int total=0,greatthan=0, lessthan=0;
cout<< "Please enter 5 numbers\n";

for(int number=0; number<5; number++)
{
cin>>number;
total=total+number;

if(number>0)
{//greater than input
greatthan=greatthan+number;
}
if(number<=0)
{//less than or equal to zero input
lessthan=lessthan+number;
}


}
cout<<greatthan<<"\n";
cout<<lessthan<<"\n";
cout<<total<<"\n";


return 0;
}

When the 5 numbers are intered it sometimes works and other times it doesnt. Not to sure why?

Write a program, using a loop structure (while, do-while, etc.),
that reads in 5 whole numbers (positive, negative, or zero) and that:

1. outputs the sum of all the numbers greater than (>) zero,

2. outputs the sum of all the numbers less than or equal (<=) to zero,

3. and outputs the sum of all the numbers.

The user enters the 5 numbers just once each (for example, 2 0 2 -1 10) and the user can
enter them in any order. Your program should not ask the user to enter the positive
numbers and the negative numbers separately. Try several examples of different input
sets to test the correctness of your program.

Here is a sample output when you run the program:

Enter 5 whole numbers: 2 0 2 -1 10
The sum of all the numbers greater than zero is 14
The sum of all the numbers less than or equal to zero is -1
The sum of all the numbers is 13
Last edited on
You should use a different variable for the for loop counter than the one that you are reading in from the user.

1
2
3
4
5
for( int i = 0; i < 5; ++i )
{
    int number;
    cin >> number;
//... 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main()
{
int sum=0;
int total=0,greatthan=0, lessthan=0;

cout<< "Please enter 5 numbers" << flush;

for(int number=0; number<5; number++)
{
  int numberIn; // use other name here than loop var for input
  cin>>numberIn;    
  total=total+numberIn;

  if(numberIn>0)
  {//greater than input
    greatthan=greatthan+numberIn;
  }
  if(numberIn<=0)
  {//less than or equal to zero input
    lessthan=lessthan+numberIn;
  }
}
cout<<greatthan<<  endl;
cout<<lessthan<< endl;
cout<<total<< endl;

return 0;
}


hth
Thanks for the help. It works just fine now. Simple mistake.
Topic archived. No new replies allowed.