For loop in a for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

19th Jul 2020, 8:49 AM
Solus
Solus - avatar
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.☺️
19th Jul 2020, 9:16 AM
v@msi😉
v@msi😉 - avatar
+ 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; }
19th Jul 2020, 9:37 AM
Abhay
Abhay - avatar
+ 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.
19th Jul 2020, 9:30 AM
Théophile
Théophile - avatar
+ 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🤔
19th Jul 2020, 9:04 AM
Abhay
Abhay - avatar
+ 1
Abhay Yes, he changed question. Previous he forgets one }
19th Jul 2020, 9:40 AM
v@msi😉
v@msi😉 - avatar
+ 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 ...
19th Jul 2020, 9:43 AM
Ipang