Start learning free

LESSON 189 OF 414 · NESTED LOOPS

Print a Triangle of Stars in Scala with a for Loop

Practice O(n2) Read the full explanation

Given a positive integer n print a triangle of stars as in the example below

Example:

Input: n = 5
Output:
*
**
***
****
*****
Explanation: Print 5 lines, on ith line print i stars.
STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · NESTED LOOPS

    Print Triangle Of Stars in Scala, explained

    Problem overview

    The method printStars takes a positive Int named n and prints a triangle of stars. Row 1 has one star, row 2 has two, and so on up to row n, which has n stars. The method returns nothing; its job is the printed output. For n = 5 the output is:

    *
    **
    ***
    ****
    *****
    

    Approach: grow one row into the next

    Look at how consecutive rows relate. Each row is the previous row with one more star at the end. That suggests a loop that keeps the current row in a string variable, adds a star to it, and prints it. After n passes, n rows have been printed and each is one character longer than the one before.

    No row has to be built from scratch, and there is no inner loop to count stars. The string carries the previous row with it.

    Step by step

    1. Declare the row. Create a var named str set to the empty string "". It is a var because it changes in every pass.
    2. Loop once per row with for (i <- 0 until n). The range 0 until n excludes its upper bound, so it produces exactly n values. The variable i only counts the rows and is never used in the body.
    3. Add a star to the end of str with +=. On the first pass the string holds one star, on the second pass two, and so on.
    4. Print the row with println(str), still inside the loop. Each println ends with a newline, so every row gets its own line. Printing after the loop would show only the last, longest row.

    The solution in Scala

    class Solution {
        def printStars(n: Int): Unit = {
            var str = ""
            for (i <- 0 until n) {
                str += "*"
                println(str)
            }
        }
    }
    

    The Scala details worth knowing:

    • until versus to. 0 until 5 covers 0, 1, 2, 3, 4 and stops before 5. 1 to 5 covers 1 to 5 inclusive. Both give five iterations, so either works here, because the loop variable isn't used.
    • The result type Unit. Unit is Scala's "no useful value" type, similar to void in other languages. The method runs for its side effect, printing.
    • += on a string. Strings can't be modified, so str += "*" builds a new string and stores it in str, which is why str must be a var. A val would not compile with +=.
    • println versus print. println adds a line break after the text. print doesn't, and using it would run all the rows into one line, such as ****** for three rows' worth of stars.
    • An alternative. Scala can repeat a string with *, so "*" * i is i stars. A loop for (i <- 1 to n) println("*" * i) prints the same triangle. The lesson's version shows how a value is built up from one iteration to the next.

    Complexity

    Row k has k stars, so printing all rows writes 1 + 2 + ... + n = n(n + 1) / 2 characters. The output alone makes the time O(n^2). The string str reaches length n, so the extra space is O(n). Each += copies the current row, which is within the same quadratic total.

    Edge cases and common mistakes

    • n = 1. One pass, one row with one star.
    • n = 0 or negative. The task says n is positive, but for these values the range is empty, nothing is printed and the method returns normally.
    • Printing outside the loop. Only one row appears.
    • Resetting str inside the loop. If the declaration moves into the loop body, every row has just one star.
    • Off-by-one ranges. 0 until n - 1 prints one row too few, and 0 to n prints one too many.
    • Using print. Without the line break, the rows run together.

    Testing

    • n = 1 prints one line: *.
    • n = 3 prints *, ** and *** on three lines.
    • n = 5 prints the five-row triangle shown above.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free