+ 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; }
4 Respostas
+ 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.
+ 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.
+ 2
what is 2 × 3
+ 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 :)