In this post, we will see how to print the following pyramid pattern.
Problem
Input : n = 4
Output :
1
3*2
4*5*6
10*9*8*7Input : n = 5
Output :
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
Output :
1
3*2
4*5*6
10*9*8*7Input : n = 5
Output :
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
Solution
If you notice the pattern we need to print odd rows in increasing order and even rows in decreasing order.
We will use two for loops and three variables to achieve this pattern.
Three variables:
- row: It denotes to current row
- col: It is the number which you actually prints
- num: It actually controls the number upto which you are going to print in a row.
Java program to print 1 3*2 4*5*6 pattern in java
package org.arpit.java2blog;
// Java implementation to print the
// following pyramid pattern
public class PyramidPattern {
/* method to print the following pyramid
// pattern
* 1
3*2
4*5*6
10*9*8*7
*/
static void printPattern(int n)
{
int col, num = 0;
// loop for row
for (int row = 1; row <= n; row++) {
// when row number is odd,then print in increasing order.
if (row % 2 != 0) {
// printing in ascending order
for (col = num + 1; col < num + row; col++)
System.out.print(col + "*");
System.out.println(col++);
// update value of 'num'
num = col;
}
// when row number is odd,then print in decending order.
else {
// update value of 'num'
num = num + row - 1;
// print numbers with the '*' in
// decreasing order
for (col = num; col > num - row + 1; col--)
System.out.print(col + "*");
System.out.println(col);
}
}
}
// Driver program to test above
public static void main(String args[])
{
int n = 5;
printPattern(n);
}
}
Time Compexity: O((n (n + 1)) / 2)
That’s all about printing the pattern 1 32 456 pattern in java.