## thinfineline

Ok, I'm writing a simple for loop with an accumulator for my class tonight and can't figure out what I'm doing wrong. I want the program to accept the first 10 even numbers from the keyboard and add them up and display an error message if someone enters an odd number, heres what I've got so far and the only real problem I'm having is getting the numbers to add up correctly. If some one could give me a quick response it would be great... Thanks so much.

``````// This program will accept and sum the first 10 even numbers as read from the keyboard.
#include <iostream>
using namespace std;
//constants
const int terminatingvalue= 10;const int two=2;const int zero=0;

int main ()
{
//Variables
int ctr=1;int num;int sum=0;

// procces
for (int ctr=1; ctr<=10; ctr++)
{
cout<<"Enter a number"<<endl;
cin>>num;
if (num%two==zero)
{
sum=sum+num;
ctr++;
}
else

cout<<"Enter a number"<<endl;
cin>>num;

}
cout<<"Total is:"<<sum<<endl;
//output

return 0;
}
``````

## vmanes 1,165

You're doing input of num twice in the loop, but only adding it once.

## Sci@phy 97

You should use while loop, not for.

And you haven't declared 'two' and 'zero'.
Why don't you simply put 2 and 0?

## thinfineline

My teacher said it had to be a for loop and had to declare 2 and 0 and type them out (yeah she's a little nuts). Take the second num input out worked for getting it to add correctly but now my counters off it's only accepting 6 numbers not 10.

## Sci@phy 97

because your for loop is counting for you, and still, you are counting for yourself in
if (num%two==zero)
{
sum=sum+num; `ctr++;` }

## thinfineline

That fixed it. I'm really sorry about the stupid questions, this is my first programming class and I'm having a really hard time with it. Thanks a bunch.

Wes

## chococrack 74

If you leave it as is, it will only perform 10 repetitions of the loop, including invalid inputs. Then you'd only get the first 10 - (number of errors) even integers in your summation. My suggestion is this:

``````for (int ctr=1; ctr<=10; )
{

cout<<"Enter a number"<<endl;
cin>>num;
if (num%two==zero)
{
sum=sum+num;
ctr++; // only increment when a valid summation occurs
}
else