Help with "for" loop

Oct 15, 2013 at 7:36pm
Hello,

I am a beginner in C++ and I was looking at a problem involving a "for" loop. I do not understand how to get to the answer. I've successfully compiled the code to verify the answer and it was the same.

If someone could please run me through this. Thank you :)

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main(){
  int x = 0, i = 1
  for (; (i++) <= 5; i+=3)
      --x;
  cout << x + i << endl;
return 0;
}


The right answer is 8, but the answer I get is 5.

The way I do it is i starts 1, than gets brought up to 2 since 2 is smaller or equal to 5, it is incremented by 3. This results in 5. Then 5 gets brought up to 6 and the for loop fails. Therefore, the loop ran once and x + i = 6 + (-1) = 5.
Oct 15, 2013 at 7:50pm
Please, put a ; (semicolon) after i = 1 in the line 5:

int x = 0, i = 1;
Last edited on Oct 15, 2013 at 7:53pm
Oct 15, 2013 at 7:53pm
The way I do it is i starts 1, than gets brought up to 2 since 2 is smaller or equal to 5, it is incremented by 3.


That would be true if you were using a prefix increment, but you're using a postfix increment.

We begin with i equal to 1. The loop condition compares i before the increment ( 1 <= 5 ) and sets i to i+1 (2). Since the loop condition evaluates to true, the body of the loop is executed making x -1, and then i is increased by 3, making it 5.

We begin this iteration with i equal to 5. The loop condition compares i before the increment (5 <= 5) and sets i to i+1 (6). Since the loop condition evaluates to true, the body of the loop is executed making x -2 and then i is increased by 3 making it 9.

We begin this iteration with i equal to 9. The loop condition compares i before the increment (9 <= 5) and sets i to i+1 (10). Since the loop condition evaluates to false, the body of the loop will not be executed and neither x nor i will change again leaving us with:

i has the value 10 and x has the value -2. -2 + 10 is 8.
Topic archived. No new replies allowed.