Nested Loops in C++

Nested loops in C++

  • C++ allows 256 levels of nesting
  • It is a procedure to construct a loop inside another loop body

Execution flow

  • When we are working with nested loops always 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 Outer loop
  • Until outer loop test condition becomes false outer loop executes n number of times

C++ program to print multiplication tables within a given range

main() 
{

int n;
cout<<" tables up to:";
cin>>n;

for(int i=1;i<=n;i++)//outer most for
{//increments i

for(int j=1;j<=10;j++)//for inside a for
{
cout<<i*j<<"\t";//increments j for each i
}

cout<<"\n";//next table in new line
}

}

O/P

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100
  • In the first iteration i=1, now control goes to innermost loop it executes  10 times  by incrementing j=1 to j=10 so that we will get 1 2 ..10
  • Now the inner loop fails and control goes to outer loop and i becomes 2 and control goes to the inner loop which will execute j=1 to 10 so that we will get 2 4 6 8…20
  • This process continues until i value becomes 10

C++ program to print the following pattern

enter no of rows:5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Code

main() 
{

int n,count=0;
cout<<"enter no of rows:";
cin>>n;

for(int i=1;i<=n;i++)
{

for(int j=1;j<=i;j++)
//(j<i) makes 1st row one number 2nd row 2 numbers 3rd row 3 numbers...
{
cout<<++count<<"\t";
}
cout<<"\n";

}

}

C++ program to print the following pattern

1
22
333
4445
55555
55555
4444
333
22
1
Code:
main()
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
cout<<i;
}
cout<<"\n";
}

for(int i=5;i>=1;i--)//print the same again from reverse
{
for(int j=1;j<=i;j++)
{
cout<<i;
}
cout<<"\n";
}
}