Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
pattern
java

How to generate a right angle triangle in Java using stars

Vinisha Maheshwari

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.

  1. Initialization condition: Here, we declare and initialize the variable that we use in the loop.

  2. Testing condition: Here, we add a Boolean expression to test the condition for evaluation.

  3. Statement execution: Once the condition is evaluated to be true, the body of the loop is executed.

  4. Increment/Decrement: This updates the variable for the next iteration.

  5. 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.

Right Angle Triangle pattern

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

Right angle triangle pattern using stars in Java

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 Scanner class 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 for loop to iterate through rows from a = 0 to a < n.

  • The condition of the outer loop is true then, in line 9, the inner loop runs to print the start (*) character up to a times to print each row of the right angle triangle.

  • Then, the cursor comes to the next line and the process is repeated until n rows of the triangle are printed.

In this way, we can use for loops to generate a right-angle triangle pattern using stars in Java.

RELATED TAGS

communitycreator
pattern
java
RELATED COURSES

View all Courses

Keep Exploring