Page 239 - CA_Blue( J )_Class9
P. 239
10.1 NESTED FOR LOOP
When a “for loop” is placed inside another “for loop”, is called a nested for loop. Let us take a look at the syntax
of a nested for loop.
for (initialization; condition; increment) // step of outer loop
{
for (initialization; condition; increment) // step of inner loop
{
// statement of inner loop
}
// statement of outer loop
}
Let us take an example:
Program 1 Write a program to print the factorials of all the even numbers from 1 to 5.
1 class nested_for
2 {
3 public static void main()
4 { int i,j,f;
5 System.out.println("Factorial of all even numbers between 1 and 5 ");
6 for(i=2;i<=4;i=i+2)
7 {
8 if((i%2)==1)
9 continue;
10 System.out.print("Factorial of " + i + " is : ");
11 f=1;
12 for(j=1;j<=i;j++)
13 {
14 f=f*j;
15 }
16 System.out.println(f);
17 }
18 }
19 }
You will get the following output:
Nested Loop 237

