for loop help

can anyone suggest how to turn this into a for loop?
I know that for a for loop, you have to (initialize it; set up a counter; and increment the counter). I'm stuck on that. This returns 15, but I'm not exactly sure of how that is even.....

int incr = 2, num = 3, sum = 0;
while (9 > num) {
sum = sum + num;
num = num + incr;
}
cout << “Sum: “ << sum << endl;
A for loop is easy to understand once it is explained to you. There are 3 different parts of a for loop, the initialation, the if function, and then the incremetion.

1
2
3
4
for(int x=0 ; x < 10 ; x++)
{
   // Do something
}


Here x is setup as 0 initially, then the for function runs because x is 0 and is less then 10 so it is true. Then once it is complete x++ is run making x equal to 1. This completes the first loop. Now the second part is compared once again as if it was an if statement, here is would be x < 10 or 1 < 10 so it would be true and ran again. Once complete, x++ runs making x equal to 3. this will keep running until x is equal to 10 were 10 is not less then 10 and the statement fails, booting you out of the for loop.

Some people declare x before the for loop but it is better to declare it inside if you don't intend to use it once it is over so that you can reuse the variable in another for loop later if you choose and get back the memory space (larger programs memory space is like gold).

In your situation, your num variable is your counting function so you would do this

1
2
3
4
5
6
int sum = 0, incr = 2
for(int num = 0 ; 9 > num ; num+=incr)
{
   sum += num;
}
cout << "Sum: " << sum << endl;


I use += because it is basically the same thing as what you were doing here. You can do it your way if you like though but this way saves on typing (speed it doesn't matter as far as I know yet).

Hope you understand it better now.

The reason your output was 15 because your while statement which worked like a for statement the way you set ut up added this:

First run:
sum goes from 0 to 3
num goes from 3 to 5

Second run:
sum goes from 3 to 8
num goes from 5 to 7

Third run:
sum goes from 8 to 15
num goes from 7 to 9

Now 9 is not greater then 9 so it exits. This means your while statement only ran 3 times (making it easy to explain this).
Last edited on
Thanks for that great reply. I was desk-checking the while and saw that num was incrementing to 9, but missed that the return would be 15 for the sum. I was hanging up on the 9 > 9....
I coded the for loop as per your example but it returned 20, then I noticed that num was initialized to 0. When I changed that to 3 it returned 15. So I guess I'm learning something. Thanks for your help. Much appreciated!!
Topic archived. No new replies allowed.