Right Triangle Star Pattern

beginner Pattern Printing

Problem

Read n and print a right triangle of stars with n rows. Row 1 has 1 star, row 2 has 2 stars, and so on.

Constraints

  • 1 <= n <= 50

Examples

Input

3

Output

*
**
***

Solutions

Best approachTime O(n^2)Space O(1)

The row number is also the number of stars. One outer loop goes over the rows and the line is built from that many stars.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).

/*
 * Problem : Right triangle of stars.
 * Input   : One integer n (number of rows).
 * Output  : n lines of stars.
 * Approach: Use a loop for rows and build each line with stars.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method returns the text repeated "count" times. Java 11 has String.repeat for this.
static String repeat(String text, int count) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < count; i++) {
        result.append(text);
    }
    return result.toString();
}

    public static void main(String[] args) {
        int rows = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers go from 1 to rows.
        for (int row = 1; row <= rows; row++) {
            // Step 2: Row 1 has 1 star, row 2 has 2 stars, and so on.
            int stars = row;

            // Step 3: Print the stars on one line.
            System.out.println(repeat("*", stars));
        }
    }
}
Hints (2)
  1. Use one outer loop for the rows. What changes from one row to the next?
  2. Write the pattern for n = 3 on paper and count the stars in each row.