write a program in Java to display the following pattern:
Answers
Pattern Questions in Java
We see that there are 5 rows and 5 elements in each row.
So we must have an outer loop running 5 times to print 5 rows.
In the row, the number is printed times. So we must set a loop for that.
For example, in the third row, 3 is printed 3 times.
After this we need an increasing sequence to fill for the remaining elements. We run another loop for that.
Here is a Java program which prints the required pattern:
public class Pattern
{
public static void main(String[] args)
{
int i,j,k;
for(i=1;i<=5;i++) //Outer Loop of i prints 5 rows
{
//In the i^th row, we must print the number i, i times
for(j=1;j<=i;j++) //j runs from 1 to i
{
System.out.print(i+" ");
}
//After that we need an increasing sequence to fill for the remaining elements
for(k=j;k<=5;k++) //k runs from j to 5
{
System.out.print(k+" ");
}
System.out.println(); //Printing a new line after each row
}
}
}
So we must have an outer loop running 5 times to print 5 rows.
In the i^{th}ith row, the number ii is printed iitimes. So we must set a loop for that.
For example, in the third row, 3 is printed 3 times.
After this we need an increasing sequence to fill for the remaining elements. We run another loop for that.
Here is a Java program which prints the required pattern:
public class Pattern
{
public static void main(String[] args)
{
int i,j,k;
for(i=1;i<=5;i++) //Outer Loop of i prints 5 rows
{
//In the i^th row, we must print the number i, i times
for(j=1;j<=i;j++) //j runs from 1 to i
{
System.out.print(i+" ");
}
//After that we need an increasing sequence to fill for the remaining elements
for(k=j;k<=5;k++) //k runs from j to 5
{
System.out.print(k+" ");
}
System.out.println(); //Printing a new line after each row
}
}
}