+ 3

How can I understand nested loops in c++

#include <iostream> using namespace std; int main() { int i ; int j; for(i=0;i<=10;i++){ for(j=0;j<=10;j++) {} cout<< j<< endl; } return 0; }

1st Feb 2018, 4:26 PM
Yogesh Yadav
Yogesh Yadav - avatar
3 Answers
+ 8
nested for loop is executed 11 times and then i is incremented by one, and then that is repeated 11 times so j will be printed 11 times because nested for loop is empty
1st Feb 2018, 4:41 PM
Vukan
Vukan - avatar
+ 2
Try updating to this and run. It should help you see that the outer loop "i" loop runs once, then the program progresses to nested loop "j" loop which runs all 11 times before returning to the outer loop. This process is repeated until i = 10. Copy this exactly as the spacing in the cout for j is important to notice/understand the "nested" aspect. for(i=0;i<=10;i++){ cout<< "i = " << i << endl; for(j=0;j<=10;j++) { cout<< " j = " << j<< endl; } }
1st Feb 2018, 6:24 PM
Duncan
Duncan - avatar
- 2
Simply nested loop is a loop statement in a loop
2nd Feb 2018, 11:49 AM
Rashi