Java Code To Create Pyramid and Pattern
In this examples, you’ll learn to create pyramid, half pyramid, inverted pyramid, Pascal’s triangle and Floyd’s triangle sing control statements in Java.
Print half pyramid using * in Java
1 2 3 4 5 6 7 8 9 10 11 |
public static void main(String[] args) { int rows = 5; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { System.out.print("* "); } System.out.println(); } } |
Inverted full pyramid using * in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void main(String[] args) { int rows = 5; for(int i = rows; i >= 1; --i) { for(int space = 1; space <= rows - i; ++space) { System.out.print(" "); } for(int j=i; j <= 2 * i - 1; ++j) { System.out.print("* "); } for(int j = 0; j < i - 1; ++j) { System.out.print("* "); } System.out.println(); } } |
Print half pyramid a using numbers in Java
1 2 3 4 5 6 7 8 9 10 11 |
public static void main(String[] args) { int rows = 5; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { System.out.print(j + " "); } System.out.println(); } } |
Program to print half pyramid using alphabets in Java
1 2 3 4 5 6 7 8 9 10 11 |
public static void main(String[] args) { char last = 'X', alphabet = 'O'; for(int i = 1; i <= (last-'O'+1); ++i) { for(int j = 1; j <= i; ++j) { System.out.print(alphabet + " "); } ++alphabet; System.out.println(); } |
Program to print full pyramid using * in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void main(String[] args) { int rows = 5, k = 0; for(int i = 1; i <= rows; ++i, k = 0) { for(int space = 1; space <= rows - i; ++space) { System.out.print(" "); } while(k != 2 * i - 1) { System.out.print("* "); ++k; } System.out.println(); } } |
Output: