Nested Loop: Muhammad Ahmad Lecturer Cs Department
Nested Loop: Muhammad Ahmad Lecturer Cs Department
Nested Loop
MUHAMMAD AHMAD
LECTURER
CS DEPARTMENT
Loops 2
Nested Loops
Nested Loop 3
int main()
{
for(int i=1; i<=5; i++)
Output
{ 1
for(int j=1; j<=i; j++) 12
123
{
1234
cout<<j; 12345
}
cout<<"\n";
}
return 0;
}
Nested Loop 4
int main()
{
for(int i=5; i>=1; i--)
{
for(int j=i; j>=1; j--) Output
{ 54321
4321
cout<<j;
321
} 21
cout<<"\n"; 1
}
return 0;
}
Nested Loop 5
int main()
{
for(int i=5; i>=1; i--)
{
for(int j=1; j<=i; j++)
{ Output
12345
cout<<j; 1234
} 123
12
cout<<"\n";
1
}
return 0;
}
Nested Loop 6
int i=5;
while(i>=1)
{
int j=1;
while(j<=i)
{
Output
Cout<<j; 12345
j++; 1234
123
}
12
i--; 1
Cout<<“\n”;
}
Nested Loop 7
for(int i=5;i>=1;i--)
{
for(int j=1;j<=i;j++)
{
Cout<<“*”;
} Output
*****
Cout<<“\n”;
****
} ***
**
*
8
Output
*
**
***
****
*****
Now lets try a real world example of nested 9
for loop.
Write a program using for, while and do while and nested loops to display the
following outputs.
12345678910 1
123456789 *
12 ======
12345678 ***
123 *********
1234567 *****
1234 *******
123456 *******
12345 *****
12345 *******
123456 ***
1234 *****
1234567 *
123 ***
12345678 ======
12 *
123456789
1 12345678910
15
Programs: 16
Write a program using for, while and do while and nested loops to display the
following outputs.
13579 0 &
13579 02 && *
1357 024 &&& ***
1357 0246 &&&& *****
135 02468 &&&&& *******
135 0246810 &&&&& *****
13 024681012 &&&& ***
1 02468101214 &&& *
&&
&