On this page we will discuss about nested loops in C++.C++ allows 256 levels of nesting.It is a procedure to construct a loop inside another loop body. It is very important concept to understand the basics of C++ programming.Nested loop is also used in pattern printing.
Nested Loops in C++ Language
C++ allows nesting of looping structures like – For, while, Do-while, for-each etc. To allow for complex code logic and control structure.We will first look at an example syntax for nesting and then a few programs to understand how it can be done. Even though nesting is allowed for all types of loops. For loop nesting is most common. Both homogeneous and heterogeneous nesting is allowed. Example – 1. For loop within For loop / while loop within while loop 2. For loop within while loop / Do-while within for loop
Homogeneous nesting
For Loop
for (initialization; condition(s); increment) {
// statement(s) of outer loop
for (initialization; condition(s); increment) {
// statement(s) of inner loop
}
// statement(s) of outer loop
}
While Loop
while(condition(s)) {
// statement(s) of outer loop
while(condition(s)) {
// statement(s) of inner loop
}
// statement(s) of outer loop
}
Do-while Loop
do{
// statement(s) of outer loop
do{
// statement(s) of inner loop
}while(condition);
// statement(s) of outer loop
}while(condition);
Heterogeneous nesting
While all kinds of combinations of nesting can be done, we have taken an example of for loop inside a while loop and that while loop inside do-while
Example
do{
// statement(s) of do-while loop
while(condition) {
// statement(s) of while loop
for ( initialization; condition; increment ) {
// statement(s) of for loop
}
// statement(s) of while loop
}
// statement(s) of do-while loop
}while(condition);
When we are working with nested loopsalways execution starts from the outer loop test condition, if it is true control will pass to the outer loop body
Now the inner loop test condition is checked, if the inner loop test condition is true, control will pass within the inner loop until the inner loop test condition becomes false
In the inner loop if the condition becomes false control goes to the Outer loop
Until the outer loop test condition becomes false outer loop executes n number of times.
#include<iostream>
using namespace std;
int main()
{
// Declare the matrix
int mat[3][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
cout << "Matrix \n";
// Here we are using two for loops to print two matrices
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
cout << mat[i][j] << " ";
cout << "\n";
}
return 0;
}
Login/Signup to comment