Nested for loops in C++ programming , loop inside loop
Nested for loops
Nested for loops
In nested for loop the outer for loop condition is checked first if the outer loop condition is true then the next inner for loop condition will be checked and if the inner for loop condition is true then it will executed and then next and so on. The program will not terminate until the outer for loop condition is true when the outer loop condition become wrong then program will terminated. Syntax
for () { Statement 1 for () { Statement 2 }Example 1
#include<iostream.h> int main() { for(int a=1;a<2;a++) { cout<<"Cat"<<endl; { for (int b=0;b<3;b++) cout<<"Dog"<<endl; } }; system("pause"); return 0; };Output: Cat Dog Dog Dog In this example the outer loop condition is true so the Cat is printed on the screen and then the inner loop condition is checked it is also true so it will print the Dog on the screen three times and when its condition is become wrong then the outer loop condition is checked if it also wrong then program is terminated.
Example 2
#include<iostream.h> int main() { for(int a=3;a<2;a++) { cout<<"Cat"<<endl; { for (int b=0;b<3;b++) cout<<"Dog"<<endl; } }; system("pause"); return 0; };Output: no output will display This is because the outer for loop condition is wrong and the inner for loop condition is true but still no output will displayed.
Example 3
#include<iostream.h> int main() { for(int a=1;a<2;a++) { cout<<"Cat"<<endl; { for (int b=4;b<3;b++) cout<<"Dog"<<endl; } }; system("pause"); return 0; };Output : Cat In this example the outer for loop condition is true so the statement which is defined in the body of for loop will executed but the inner loop condition is wrong so it will not executed.
Example 4
#include<iostream.h> int main() { for(int a=1;a<3;a++) { cout<<"Cat"<<endl; { for (int b=0;b<2;b++) cout<<"Dog"<<endl; } }; system("pause"); return 0; };Output: Cat Dog Dog Cat Dog Dog
It this example the outer for loop and the inner for loop condition is true so both of the statement will executed. In this example the outer loop condition is true so the Cat will display on the screen then the value of variable used in outer for loop is increases by 1 and the next inner loop condition will be checked and it is also true in this case so it will print the Dog on the screen two time because of it condition and then its condition will become wrong then compiler jumps on the outer loop and checked its condition and it true so it will executed and so on.