InterviewSolution
| 1. |
Write a program in Java to display the following pattern: |
Answer» Pattern Questions in JavaWe 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 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 } } } |
|