Table of Contents
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.