In this tutorial you will learn about the Java Program to Print Invert Triangle and its application with practical example.
In this tutorial, we will learn to create a Java program that will Print Inverted Triangle using Java programming Language.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output
- Class and Object.
- Basic Java programming.
- Loops in Java.
- Nested for loop in Java.
Invert Triangle of Star
To print Inverted Triangle Star patterns in Java , we will use nested for loops. The outermost loop is responsible for the number of rows in star (*) of Inverted Triangle,whereas inner one loop will print the required number of stars * in each row.
Java Program to Print Invert Triangle
In this program we will print Inverted Triangle of Star using nested “For” loop and a while loop. We would first declared and initialized the required variables. Then we will create the “Inverted Triangle” of Star using below program.Let’s have a look.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// Java program to Print Reverse full Pyramid // Importing input output classes import java.io.*; class revtriangle { public static void main(String[] args) { // Declaring and initializing variable to int num = 5; int i = num, j; // Nested while loops // Outer loop // Till condition satisfied while (i > 0) { j = 0; // cheking Condition check while (j++ < num - i) { // Print whitespaces System.out.print(" "); } j = 0; // Inner loop // Condition check while (j++ < (i * 2) - 1) { // Print star System.out.print("*"); } // so next line System.out.println(); // reversing the pyramid value i--; } } } |
Output
Java Program to Print Invert Triangle
In the above program, we have first declared and initialized a set variables required in the program.
- num = it will hold size or pyramid
- i and j= it will use to iterate loops.
Now we going to run loops
Outermost loop to iterate through a number of rows as initialize . Now,
Run an inner loop from 1 to ‘i-1’
As you can see in the image above ,and again run another inner loop from 1 to rows * 2 – (i × 2 – 1) that will print over desire output.
We had printed reverse pyramid star(*) pattern using the following methods.