0
For loop in a for loop
The output is 7 (and not 8) for int x; for(x=0; x<4; ++x) { for(int y=0; y<4; ++y) { x=x+y; } } cout<<x; What is the logic for this?
6 Answers
+ 3
The output is 7
Because
1st run x=0
2nd run x=1
3rd run x=3
4th run x=6
And it comes out from the for(y)
After Increment in for(x) x=7, checks the condition and comes out.âșïž
+ 3
Did question changed or I read it wrong ?
I calculated for this
int main() {
int x;
for(x=0; x<4; ++x) {
for(int y=0; y<4; ++y) {
x=x+y;
}
cout<<x;
}
return 0;
}
+ 2
Abhay as Krishna vamsi explained, when the 'y' loop is over, x is 6.
However, it doesn't quit directly the 'x' loop, since Ă for loop is structured like this :
- condition
- block
- increment
So it increments 'x', checks if 'x < 4' and exits the loop.
+ 1
Well the output is 6 ,I had to even run it in playground to make sure as I calculated it was 6 by writing but cudn't figure out how it is 7 or 8đ€
+ 1
Abhay Yes, he changed question. Previous he forgets one }
+ 1
I don't think it's a good idea to alter loop counter value except for incrementing/decrementing it per loop cycle.
Just saying ...