Hi I have a question regarding for-loops. What value would be saved in x?
1 2
int x = 0;
for( int i = 0; i < 4; x += i++ );
As I understand, the loop starts from initial 0 with condition that i<4. It will also increment by 1. But I do not get how the value of x can be determined. Any help would be appreciated :) Thanks
#include <iostream>
int main() {
int x = 0;
for ( int i = 0; i < 4; x += i++ ) {
std::cout << "i=" << i << " x=" << x << '\n';
}
std::cout << "final x=" << x << '\n';
return 0;
}
It is unclear to me why x=6 is. I know this is a post increment which means we return the value and then increment it if I have understood it correctly. So that means x and i starts from 0 and will be incremented. First loop: x=0 i=1; second loop: x=1 i=2 and so on. Am I understanding this correctly? But how does x add up to 6? because i stops at 3.
I'm really sorry, I tried looking up tutorials but it doesn't provide any concrete explanation to this. I found a post with a similar topic : http://www.cplusplus.com/forum/beginner/125466/
but there are some things I didn't quite understand particularly this:
1 2 3 4 5
int x = 0;
int y = 5;
x = y++; // x = 5, y = 6
x = ++y; // x = 7, y = 7;
The condition is not true only if 3 < i.
When 3==i, the condition is still true, the loop body is executed and the increment statement x += i++ is evaluated.
On the next time 3 < i (because i is already 4), the loop condition is false, and the looping ends.
for ( int i = 0; i < 4; x += i++ );
// is same as
for ( int i = 0; i < 4; x += i++ )
{
}
// is same as
for ( int i = 0; i < 4; )
{
x += i++;
}
// is same as
for ( int i = 0; i < 4; )
{
x += i;
++i;
}
// is same as
for ( int i = 0; i < 4; ++i )
{
x += i;
}
All these answers are good, but they have kind of missed the small point of x += . So after x becomes larger than zero you start with that number and then add to it. As Grey Wolf wrote Loop 4, i = 3 so x = x + 3 = 6 remember x starts out as 3 before you add three to get 6.