Help with Loops

hello. I'm a beginner at c++ and I need to write a program that reads a set of integers and then finds and prints the sum of the even and odd integers. The program cannot tell the user how many integers to enter. I need to have separate totals for the even and odd numbers. what would I need to use so that I can read whatever number of values the user inputs and get the sum of even and odd?
I read many places to use arrays - we haven't covered that topic in class.
> what would I need to use so that I can read whatever number of values the user inputs
1
2
int number;
while( std::cin>>number )
If you have not covered arrays, I'd suggest doing the following:

Have two variables that keep track of the totals for the Odd and Even numbers entered:

int oddTotal

int evenTotal

From there, you can have a sentinel controlled while loop. This is just fancy talk for a while loop that continues to execute until an ending value is entered, like -1.

That would look something like this:

1
2
3
4
while(number != -1)
{
   cin >> number;
}


After the number is input, you can then determine if it is odd or even and add it to the appropriate total.

1
2
3
4
5
6
7
8
9
10
11
while(number != -1)
{
   if(isEven(number))
      evenTotal = evenTotal + number;
   else if(isOdd(number))
      oddTotal = oddTotal + number;
   else
      // default case, if doesn't match any of the above

   cin >> number;
}


The isEven() and isOdd() functions would take the number and return a bool if the number was even or odd.

Does that work for your purposes?
Last edited on
Topic archived. No new replies allowed.