NESTED LOOP
Fahim Morshed
Lecturer
Department of CSE
University of Liberal Arts Bangladesh
1
•
nested loops in C
C programming allows to use one loop inside another loop.
• Syntax: nested for loop statement in C is as follows −
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
• Syntax: nested while loop statement in C is as follows −
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
2
}
nested loops in C
• Syntax: nested do while loop statement in C is as follows −
do {
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
3
Example of Nested for loop
What is the code for the
#include <stdio.h>
following output ? int main()
{
Output int i, j;
****
**** for (i=1; i<=5; i++)
{
****
for (j=1; j<=4; j++)
**** {
**** printf("*");
}
printf("\n");
}
return 0;
}
4
Example of Nested for loop
What is the code for the
#include <stdio.h>
following output ? int main()
{
Output int i, j;
*
** for (i=1; i<=5; i++)
{
***
for (j=1; j<=i; j++)
**** {
***** printf("*");
}
printf("\n");
}
return 0;
}
5
Example of Nested for loop
What is the code for the
#include <stdio.h>
following output ? int main()
{
Output int i, j;
1
12 for (i=1; i<=5; i++)
{
123
for (j=1; j<=i; j++)
1234 {
12345 printf("%d ", j);
}
printf("\n");
}
return 0;
}
6
Example of Nested while loop
What is the code for the
#include <stdio.h>
following output ? int main()
{
Output int i, j;
1 i = 1;
12 while (i<=5)
{
123
j = 1;
1234 while(j<=i)
12345 {
printf("%d ", j);
j++;
}
i++;
printf("\n");
}
return 0;
}
7
Example of Nested do while loop
#include <stdio.h>
What is the code for the int main()
following output ? {
int i,j;
Output
* i=1;
do
**
{
*** j=1;
**** do
***** {
printf("*");
j++;
} while(j <= i);
printf("\n");
i++;
}while(i <= 5);
return 0;
}
8
More Example
#include <stdio.h>
What is the code for the
following output ? int main()
{
Output int i, j;
1 2 3 4 5
for(i=1; i<=10; i++)
2 4 6 8 10
{
3 6 9 12 15 for(j=1; j<=5; j++)
4 8 12 16 20 {
5 10 15 20 25 printf("%d\t", (i*j));
6 12 18 24 30 }
7 14 21 28 35
printf("\n");
8 16 24 32 40
}
9 18 27 36 45
10 20 30 40 50 return 0;
}
9
Write a code to find out a number is prime or not
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
} 10
End
11