How to generate a right angle triangle in Java using stars
In this article, we will discuss how to make a right angle triangle pattern using stars in Java.
Solution approach
We will use for loops to generate a right-angled triangle pattern using stars in Java.
Loops are used to repeat the set of instructions while the pattern is being generated, and simultaneously allow the given condition to be evaluated as true.
-
Initialization condition: Here, we declare and initialize the variable that we use in the loop.
-
Testing condition: Here, we add a Boolean expression to test the condition for evaluation.
-
Statement execution: Once the condition is evaluated to be
true, the body of the loop is executed. -
Increment/Decrement: This updates the variable for the next iteration.
-
Loop termination: When the condition becomes
false, the loop terminates, marking the end of its life cycle.
Let’s look at an image of the pattern that we will generate.
Syntax
for (initialization_condition; testing_condition; increment/decrement)
{
//body of the loop
}
Code
Let’s look at the code snippet below to understand this better.
Input a number for the height/length of the triangle.
import java.util.Scanner;class RightTriangle {public static void main(String args[]){Scanner sc = new Scanner(System.in);int n=sc.nextInt();int a, b;for(a = 0; a < n; a++) {for(b = 0; b <= a; b++) {System.out.print("* ");}System.out.println();}}}
Enter the input below
Explanation
-
In line 1, we imported the Java library to read the input value from the user.
-
In line 5, we create an object of the
Scannerclass to read the input from the console (which will denote the height of the right angle triangle). -
In line 6, we read the input value and store it in variable
n. -
In line 8, we run the outer
forloop to iterate through rows froma = 0toa < n. -
The condition of the outer loop is true then, in line 9, the inner loop runs to print the start (
*) character up toatimes to print each row of the right angle triangle. -
Then, the cursor comes to the next line and the process is repeated until
nrows of the triangle are printed.
In this way, we can use for loops to generate a right-angle triangle pattern using stars in Java.