Java program to print Inverted Pyramid star pattern program – We have written below the print/draw Inverted Pyramid asterisk/star pattern program in four different ways with sample example and output, check it out. At the end of the program, we have added compiler so that you can execute the below codes.
- Using For Loop
- Using While Loop
- Using Do While Loop
Using For Loop
1) Read the value and store that value in the variable n.
2) To iterate through rows run the outer loop with the structure for(int i=n;i>0;i–).
3) To iterate through rows run the inner loops.
4) 1st inner loop prints space if i>0 && j<n-i.
5) 2nd inner loop prints character if i>0&&j<(i*2)-1
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 |
import java.util.Scanner; public class PITangle { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); for(int i=n;i>0 ;i--) { for(int j=0;j<n-i;j++) { System.out.print(" "); } for(int j=0;j<(i*2)-1;j++) { System.out.print(c); } System.out.println(); } } } |
Output:
1 2 3 4 5 6 7 8 |
Enter N : 5 Enter Symbol : . ......... ....... ..... ... . |
Using While Loop
1) Outer while loop iterate until i>0 is false.
2) 1st inner while loop prints space if the condition j++<n-i is true.
3) 2nd inner loop prints character if the condition j++<(i*2)-1 is true.
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 |
import java.util.Scanner; public class PITangle { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); int i=n,j; while(i>0) { j=0; while(j++<n-i) { System.out.print(" "); } j=0; while(j++<(i*2)-1) { System.out.print(c); } System.out.println(); i--; } } } |
Output:
1 2 3 4 5 6 7 8 9 |
Enter N : 6 Enter Symbol : * *********** ********* ******* ***** *** * |
Using Do-While Loop
1) The outer do-while loop iterates until while(–i>0) is false.
2) The 1st inner loop prints space until the condition j++<n-i is false.
3) The 2nd inner loop prints the character until the condition j++<i*2-2 is false.
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 |
import java.util.Scanner; public class PITangle { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); int i=n,j; do { j=0; do { System.out.print(" "); }while(j++<n-i); j=0; do { System.out.print(c); }while(j++<i*2-2); System.out.println(); } while(--i>0); ; } } |
Output:
1 2 3 4 5 6 7 8 9 |
Enter N : 6 Enter Symbol : ^ ^^^^^^^^^^^ ^^^^^^^^^ ^^^^^^^ ^^^^^ ^^^ ^ |