K.E.
CARMEL SCHOOL, AMTALA
COMPUTER
CLASS–IX NESTED LOOP PROGRAM–02
Nested Loop 02
Write a program in Java to display the following pattern :
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Code
import java.io.*;
import java.lang.*;
import java.util.*;
class Pattern2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows : ");
int n = sc.nextInt( );
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(i + "\t");
}// 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<=n; i++)
for(int j=1; j<=i; j++)
Initially, value of n = 5
First Row, i=1, 1<=5 True, j=1, 1<=1 True Print 1
j=2, 2<=1 False, inner for loop ends.
Second Row, i=2, 2<=5 True, j=1, 1<=2 True Print 2
j=2, 2<=2 True Print 2 2
j=3, 3<=2 False, inner for loop ends.
Third Row, i=3, 3<=5 True, j=1, 1<=3 True Print 3
j=2, 2<=3 True Print 3 3
j=3, 3<=3 True Print 3 3 3
j=4, 4<=3 False, inner for loop ends.
Fourth Row, i=4, 4<=5 True j=1, 1<=4 True Print 4
j=2, 2<=4 True Print 4 4
j=3, 3<=4 True Print 4 4 4
j=4, 4<=4 True Print 4 4 4 4
j=5, 5<=4 False, inner for loop ends.
Fifth Row, i=5, 5<=5 True j=1, 1<=5 True Print 5
j=2, 2<=5 True Print 5 5
j=3, 3<=5 True Print 5 5 5
j=4, 4<=5 True Print 5 5 5 5
j=5, 5<=5,True Print 5 5 5 5 5
j=6, 6<=5, False, inner for loop ends.
Sixth Row, i=6, 6<=5 False, outer for loop ends.