Presentation of Nested Loop
Presentation of Nested Loop
• #include<iostream>
• using namespace std;
• int main()
• {
• int i,j;
• for(i=1;i<=5;i++)
• {
• for(j=1;j<=5;j++)
• cout<<"*";
• cout<<endl;
• }
• }
Output:
* * * * *
* * * * *
* * * * *
* * * * *
1.Nested For Loop:
It can be defined as a loop with in another for loop is called nested for loop.
Nested loop is mostly used for dealing two-dimensional array.
It is most widely used loop in nested loop.
Syntax:
for(initialization; condition; increment / decrement) //outer loop
{
for (initialization; condition; increment / decrement) //inner loop
{
statement;
}
}
Flowchart
Of Nested For
Loop:
For Example:
• Write a program to show this series by using nested For loop
#include<iostream>
using namespace std;
int main()
{
int i , j;
for(i=1 ; i<=5; i++) //outer loop
{
for(j=1;j<=i;j++)
cout<<"*";
cout<<endl;
}
}
Output:
*
* *
* **
* ***
* ****
2.Nested while-loop :
•A nested while loop is a while statement in which another while
statement is called nested while statement.
• Working:
#include<iostream>
using namespace std;
int main()
{
int n , I , j;
cout<<“Enter numbers of rows:”;
cin>>n;
i=1;
while(i<=n) //outer loop for printing rows
{
while(j<=5) //inner loop for printing numbers
{
cout<<j<<" ";
j++;
}
cout<<endl;
i++;
return 0;
}
}
Output :
12345
12345
12345
3.Nested do-while-loop:
• Nested do while loop is a loop in which another do while loop.
• It is loop in which another loop.
• In this loop structure , inner loop executes multiple times for each
iteration of outer loop
• Syntax:
do {
statement(s);
do
statement(s);
}
while(condition);
}
while(condition);
Working:
Nested do while loop is a type of nested loop in which inner loop is executed
only when outer loop is true.
Example:
Write a program to show this sequence by using nested do while loop.
1
1 2
1 23
1 234
1 2345
#include<iostream>
using namespace std;
int main()
{
int i , j , n ;
cout<<“Enter numbers of rows:”;
cin>>n
i=1;
do
{
j=1;
do
{ //inner loop body.
cout<<j<<“ “;
j++;
}
while(j<=i); //for printing numbers
cout<<endl;
i++;
}
while(i<=n); //for printing rows
return 0;
}
Flowchart
Of Nested Do-
While Loop:
Advantages of Nested loop:
• They can be useful for iterating through multi-dimensional
data
structures, such as 2 D array.
• It allow developer to use multiple complex iteration and
repetitive tasks with greater efficiency.
• Nested
loop allow user to iterate over element with in
elements
• For loop is mostly used in nested loop
Any Question?
Thank You Very Much For Your
Attention……