Confussion over output

Why is k equal to 17? I understand that i is 5, but how is 0+5=17?

1
2
3
4
5
6
7
8
9
10
11
12
13
 #include<iostream>
using namespace std;
void main()
{
	int i, j, k = 0;

	for (i = 1; i < 5; i++)
		for (j = 0; j < i; j += 2)
			k += i;
	cout << k << endl;
	
	system("PAUSE");
} // main 
You're forgetting the inner loop, indexed by j.
I understand that i is 5,

No, it is not. It is 5 only after the loop.

While the braces are optional for single statement bodies, they could be used to emphasize the code structure:
1
2
3
4
5
6
7
8
9
for (i = 1; i < 5; i++)
{
  for (j = 0; j < i; j += 2)
  {
    k += i;
  }
}
// i==5, when execution reaches this line. Not before.
cout << k << endl;
Topic archived. No new replies allowed.