0
Can someone pls explain the different output in this 2 for loops c++
#include <iostream> using namespace std; int main() { int i; for(i = 0; i < 4; ++i){ for(int j = 0; j < 4; ++j){ i = i + j; cout<<i; //0136 } //cout<<i; //6 } //cout<<i; //7 return 0; }
1 Answer
+ 5
In the given code two for loops are nested.
The outer one executes 4 time and the one inside executes its statement block :i=i+j; 4 times for each iteration of outer for loop.
One may think inner most statements will be executed 4*4 times but this isn't the case as because we are modifying counter of outer for in inner for.
Well , I think I'm confusing you here š
š
. Let's see how it works.
first iteration of outerfor i=0;
first iteration of innerfor j=0
i=i+j=0+0=0
prints=>0
second iteration of innerfor j=1
i=i+j=0+1=1
prints=>1
third iteration of innerfor j=2
i=i+j=1+2=3
prints=>3
four iteration of innerfor j=3
i=i+j=3+3=6
prints=>6
Now! Innerfor loop breaks!š why? Because j<4 evaluates to false as j=4 now.as it breaks control reaches next statements cout<<i;
prints, =>6
i++ =>increments 6 to 7
Outerfor loop checks condition.
i<4 ....false.
Next statement executed. I. E.
cout<<i;
prints=>7.