Why the output is 6? How do the for loops affect the value of z? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why the output is 6? How do the for loops affect the value of z?

#include <iostream> using namespace std; int main() { int z=0; for(int x=0; x<2; x++){ for(int y=0; y<3; y++) ++z; } cout<<z; return 0; }

17th Jul 2018, 8:04 PM
Yelyzaveta Al-Dara
4 Answers
+ 2
It's called the loop nesting....The 2nd loop is controlled by the 1st loop.. 1st time when the x's value was 0 then then 2nd loop iterated 3 times so that the value of z becomes 3...After that, the 1st loop runs one more time and 2nd loop iterated again so the value of z become 6 and now the condition of 1st loop is false..... so the result is z equal to 6.
18th Jul 2018, 5:05 AM
Pushpajit-Biswas
Pushpajit-Biswas - avatar
+ 3
First executed loop is x = 0, x = 0,y=0, z = 1. x = 0, y=1, z = 2. x = 0, y=2, z = 3. In second loop x = 1, x = 1,y = 0, z = 4. x = 1, y=1, z = 5. x = 1, y = 2, z = 6. Condition x < 2 and y < 3, and loop is ended.
17th Jul 2018, 9:11 PM
Andrzej J1ni7a
Andrzej J1ni7a - avatar
+ 2
what is 2 × 3
17th Jul 2018, 8:10 PM
Lemuel
Lemuel - avatar
+ 1
z is initialized at 0. Each time the z++ instruction is executed, z is incremented by 1. You have a nested loop situation here, the first loop is executed twice and inside -- another loop is executed thrice, so altogether the ++z instruction is processed 2*3 times. That ends up with z at 6 :)
17th Jul 2018, 8:09 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar