Write a Java program to print pyramid numbers pattern using for loop.
package Shapes3; import java.util.Scanner; public class PyramidNum1 { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); System.out.print("Enter Pyramid Number Pattern Rows = "); int rows = sc.nextInt(); System.out.println("Printing Pyramid Number Pattern"); for (int i = 1; i <= rows; i++ ) { for (int j = rows; j > i; j-- ) { System.out.print(" "); } for(int k = 1; k <= i; k++) { System.out.print(i + " "); } System.out.println(); } } }
This program prints the pyramid pattern of numbers using a while loop.
package Shapes3; import java.util.Scanner; public class PyramidNum2 { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); System.out.print("Enter Pyramid Number Pattern Rows = "); int rows = sc.nextInt(); System.out.println("Printing Pyramid Number Pattern"); int j, k, i = 1; while(i <= rows ) { j = rows; while(j > i) { System.out.print(" "); j--; } k = 1; while(k <= i) { System.out.print(i + " "); k++; } System.out.println(); i++; } } }
Enter Pyramid Number Pattern Rows = 5
Printing Pyramid Number Pattern
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
This Java example program displays the pyramid pattern of numbers using the do while loop.
package Shapes3; import java.util.Scanner; public class PyramidNum3 { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); System.out.print("Enter Rows = "); int rows = sc.nextInt(); System.out.println("===="); int j, k, i = 1; do { j = rows; do { System.out.print(" "); } while(j-- > i); k = 1; do { System.out.print(i + " "); } while(++k <= i); System.out.println(); } while(++i <= rows ); } }
Enter Rows = 9
====
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9