info@meritcampus.com    +91-85006-22255
...
`

Write a program to print the following formation depending upon size of the matrix. Spaces between the numbers are important. Use System.out.println or System.out.print for printing.

Input (Integer) Printed Output
4 `1 1 2 1 2 3 1 2 3 4`
5 `1 1 2 1 2 3 1 2 3 4 1 2 3 4 5`

``` class PrintFormation {     public static void main(String s[])    {        printFormation(5);    }     public static void printFormation(int size)     { ```
```     } } ```
Topic:

### User comments below.All of them might not be correct.

for(int i=1;i<=size;i++){
for(int j=1;j<=i;j++){
System.out.print(j);
}
System.out.println("");

}

Posted by Dereje Goshu    2014-11-21 06:05:45

require 2 for loops outer loop with input and inner loop depends on outer loop valu e and print values.after exiting from inner loop go to new line...

Posted by Ananthoju Arun Chary    2014-11-21 08:29:53

We have to consider two loops here.One loop('for' loop) for printing values from 1 to the given parameter('size') of the method printFormation(Let the variable in first loop be i).Second loop('while' loop) is for printing line by line.(Let the variable of second loop be j).Initialize j to 1.When this j variable is less than or equal to i,then we print the corresponding value from 1 to j separated with spaces.Now after the inner loop,we need to go to new line to print another line so we can use "\n" to go to next line.This process is repeated.

Posted by Sudha Snigdha    2014-11-21 09:02:09

Here is the concept of Nested For loop, placing one for loop within the body of Another for is Nested Loop. Coming to the program, The inner and outer loops are initialised to 1,  for every increment of outer loop, i.e., 1,2,3 the inner loop executes four times i.e., 1,2,3,4 and the required output can be printed.

Posted by Sai Ram    2014-11-21 09:02:26

here we are seeing the pattern in the form of the rows and cols...Any logic if we want travel in rows and cols we must use the 2 loops(Nested loops..loop inside another loop)...1 is for row and 2nd is for col...2 for means one loop inside another loop..

in the first loop we have to set the condition that it should be repeat until it reaches the given size..means it will cover the rows...let us think user gave 5 than the condtion is row=1 and row<=5...

coming to the inner loop..this loop should repeat based on the outer loop variable..here we have to print based on row...
Ex: in 1st row we need to fill only 1 col
2nd row we need to fill 2 cols only

3rd rowl need to fill till 3rd col only..

so here we need to start an variable from 1 and should repeat till it reaches it row size...

here col=1;col<=row...

once we complete the filling the col than we should come to the next row means we use the S.o.println() or "\n"

Posted by Uday Kumar    2014-11-21 13:44:07