One of the most common questions in Programming is pattern printing, where you're asked to print different patterns according to the input given. One such problem is Pyramid Pattern printing. In this article, we will see how we can print a pyramid pattern in Java using different iterations.
Sample Input
N = 3
Sample Output
*
* *
* * *
Sample Input
N = 5
Sample Output
*
* *
* * *
* * * *
* * * * *
Using for loop
The following program prints the pyramid pattern using for loop:
Source Code
classHelloWorld { publicstaticvoidprintPyramidPattern(int N) { // Outer loop to handle number of rows for(int index1 = 0; index1 < N; index1++) { // Inner loop to print stars // on an specific row for(int index2 = 0; index2 <= index1; index2++) { // Print stars System.out.print("* "); } // Next line after each row System.out.println(); } } publicstaticvoidmain(String[] args) { // Initialize a variable int N = 5; // Display the pattern printPyramidPattern(N); } }
The following program prints the pyramid pattern using a while loop:
Source Code
classHelloWorld { publicstaticvoidprintPyramidPattern(int N) { int row = 1, column = 0; // The while loop // to loop and execute the statements // till row reaches to N while (row <= N) { while (column <= row - 1) { // Printing the pattern System.out.print("* "); column++; } row++; column = 0; // Print on new line after the next line System.out.println(); } } publicstaticvoidmain(String[] args) { // Initialize a variable int N = 5; // Display the pattern printPyramidPattern(N); } }
The following program prints the pyramid pattern using recursion:
Source Code
classHelloWorld { // function to print a row staticvoiddisplayCurrentRow(int N) { // Base conditon if (N == 0) return; System.out.print("* "); // recursively calling displayCurrentRow() displayCurrentRow(N - 1); } // function to print the pattern staticvoidprintPyramidPattern(int N, int i) { // Base condition if (N == 0) return; displayCurrentRow(i); System.out.println(); // Recursively call printPyramidPattern() printPyramidPattern(N - 1, i + 1); } publicstaticvoidmain(String[] args) { // Initialize a variable int N = 5; // Display the pattern printPyramidPattern(N, 1); } }
Now let’s print the pyramid in the inverted form:
Source Code
classHelloWorld { // Function to print the pattern staticvoidprintPyramidPattern(int N) { //Print the pattern for (int index1 = 1; index1 <= N; index1++) { for (int index2 = 1; index2 < index1 ; index2++) { System.out.print(" "); } for (int index2 = index1; index2 <= N; index2++) { System.out.print("*" + " "); } System.out.println(); } } publicstaticvoidmain(String[] args) { // The number of rows that our pattern should have int N = 5; // Display the pattern printPyramidPattern(N); } }
In this article, we discussed different types of pyramid patterns in Java. We believe that this article has provided you with a better understanding of loops in Java.