K.E.
CARMEL SCHOOL, AMTALA
COMPUTER
CLASS–IX NESTED LOOP PROGRAM–05
Nested Loop 05
Write a program in Java to display the following pattern :
1
0 0
1 1 1
0 0 0 0
1 1 1 1 1
Code
import java.io.*;
import java.lang.*;
import java.util.*;
class Pattern5
{
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 % 2) + "\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, Number of Rows (n) = 5
i=1, 1<=5 True, j=1, 1<=1 True, Print (i%2) = 1%2 = 1
j=2, 2<=1 False, inner for loop ends.
i=2, 2<=5 True, j=1, 1<=2 True, Print (i%2) = 2%2 = 0
j=2, 2<=2 True, Print (i%2) = 2%2 = 0
j=3, 3<=2 False, inner for loop ends.
i=3, 3<=5 True, j=1, 1<=3 True, Print (i%2) = 3%2 = 1
j=2, 2<=3 True, Print (i%2) = 3%2 = 1
j=3, 3<=3 True, Print (i%2) = 3%2 = 1
j=4, 4<=3 False, inner for loop ends.
i=4, 4<=5 True, j=1, 1<=4 True, Print (i%2) = 4%2 = 0
j=2, 2<=4 True, Print (i%2) = 4%2 = 0
j=3, 3<=4 True, Print (i%2) = 4%2 = 0
j=4, 4<=4 True, Print (i%2) = 4%2 = 0
j=5, 5<=4 False, inner for loop ends.
i=5, 5<=5 True, j=1, 1<=5 True, Print (i%2) = 5%2 = 1
j=2, 2<=5 True, Print (i%2) = 5%2 = 1
j=3, 3<=5 True, Print (i%2) = 5%2 = 1
j=4, 4<=5 True, Print (i%2) = 5%2 = 1
j=5, 5<=5 True, Print (i%2) = 5%2 = 1
j=6, 6<=5 False, inner for loop ends.
i=6, 6<=5 False, outer for loop ends.