K.E.
CARMEL SCHOOL, AMTALA
COMPUTER
CLASS–IX NESTED LOOP PROGRAM–03
Nested Loop 03
Write a program in Java to display the following pattern :
1
2 3
4 5 6
7 8 9 10
Code
import java.io.*;
import java.lang.*;
import java.util.*;
class Pattern3
{
public static void main(String args[ ])
{
int n = 1;
for(int i=1; i<=4; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(n + "\t");
n++;
}// end of inner for
System.out.println( );
}// end of outer for
}// end of main
}// end of class
Output
Dry Run
for(int i=1; i<=4; i++)
for(int j=1; j<=i; j++)
Initially, number of rows = 4, n = 1
i=1, 1<=4 True, j=1, 1<=1 True Print n=1 n=1+1=2
j=2, 2<=1 False, inner for loop ends.
i=2, 2<=4 True, j=1, 1<=2 True, Print n=2 n=2+1=3
j=2, 2<=2 True, Print n=3 n=3+1=4
j=3, 3<=2 False, inner for loop ends.
i=3, 3<=4 True, j=1, 1<=3 True Print n=4 n=4+1=5
j=2, 2<=3 True Print n=5 n=5+1=6
j=3, 3<=3 True Print n=6 n=6+1=7
j=4, 4<=3 False, inner for loop ends.
i=4, 4<=4 True, j=1, 1<=4 True Print n=7 n=7+1=8
j=2, 2<=4 True Print n=8 n=8+1=9
j=3, 3<=4 True Print n=9 n=9+1=10
j=4, 4<=4 True Print n=10 n=10+1=11
j=5, 5<=4 False, inner for loop ends.