Inverted Right Triangle Star Pattern

beginner Pattern Printing

Problem

Read n and print an upside-down right triangle of stars. Row 1 has n stars and every next row has one star less.

Constraints

  • 1 <= n <= 50

Examples

Input

3

Output

***
**
*

Solutions

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

For row r the number of stars is n - r + 1, so the first row is full and the last row has one star.

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 : Inverted right triangle of stars.
 * Input   : One integer n (number of rows).
 * Output  : n lines of stars.
 * Approach: Count the stars down from n to 1.
 * 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 n stars. Each next row has one star less. Example: n = 4 -> 4, 3, 2, 1.
            int stars = rows - row + 1;

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