How to Print Joint Pyramid Pattern in Java? Using Nested loops.

In our previous java program, we studied about How to Print Pyramid Pattern in Java, using nested loop.

Here’s Some more Pattern-based exercises to learn nested loops in Java. This one is second of them is printing Joint Pyramid structure as shown below:

Explanation:

You need to write a Java program to print the above pyramid pattern. How many levels the pyramid triangle would have will be decided by the user input. You can print this kind of pattern by using print() and println() method from System.out object. System.out.print() just prints the String or character you passed to it, without adding a new line, useful to print stars in the same line. While, System.out.println() print characters followed by a newline character, which is useful to move to the next line. You can also use Scanner class to get input from the user and draw a pyramid up to that level only. For example in the above diagram, the pyramid has 8 levels.

Coding:


package forwhile;

import java.util.Scanner;

public class JointPyramid {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=n; i>=1; i--)

{
for(int j=1; j<=n-i; j++)
System.out.print(" ");
for(int k=1; k<=2*i-1; k++)
System.out.print("*");
System.out.println();
}

for(int i=2; i<=n; i++)

{
for(int j=1; j<=n-i; j++)
System.out.print(" ");
for(int k=1; k<=2*i-1; k++)
System.out.print("*");
System.out.println();
}
}

}

Output:

Initiate value of n=8, The output will be:

Leave a Reply