+ 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; }
3 Antworten
+ 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
+ 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;
}
}
- 2
Simply nested loop is a loop statement in a loop