Start learning free

LESSON 190 OF 415 · NESTED LOOPS

Print a Triangle of Stars in Swift with a 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

    SWIFT · NESTED LOOPS

    Print Triangle Of Stars in Swift, explained

    Problem overview

    The method printStars(_ n: Int) prints n lines. Line number i holds i stars. It returns nothing: the output is what the method prints. For n = 5 the output is:

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

    Approach: grow one row at a time

    Each row is the previous row plus one more star. So instead of counting how many stars a row needs, keep a string that starts empty, and in every iteration add a star and print the string. The first pass prints one star, the second two, and so on, and the loop needs no inner loop and no arithmetic.

    An alternative is a nested loop, where the outer loop picks the row and the inner loop prints that many stars. It works, but it does more bookkeeping for the same output.

    Step by step

    1. Create the row string. Declare str with var, since it changes later, and set it to "".
    2. Loop once per row. for _ in 0..<n runs exactly n times. The half-open range 0..<n leaves out n. The loop only counts rows and never reads the counter, so the loop variable is _.
    3. Add a star. str += "*" appends one star to the end of the string.
    4. Print the row. print(str) writes the string followed by a newline, so each row lands on its own line. It goes inside the loop, after the star is added.

    The solution in Swift

    class Solution {
        func printStars(_ n: Int) {
            var str = ""
            for _ in 0..<n {
                str += "*"
                print(str)
            }
        }
    }
    

    The Swift details worth a closer look:

    • No return value. The method has no -> in its signature, so it returns Void. The lesson's tests look at what is printed.
    • Half-open and closed ranges. 0..<n has n values and 0...n has n + 1. Using the closed range here would print one row too many.
    • Zero rows. For n = 0 the range 0..<0 is empty, so nothing is printed.
    • Negative n. A range cannot end below its start, so 0..<n with a negative n stops the program. The lesson gives a positive n.
    • A shortcut. String(repeating: "*", count: i) builds a row of i stars in one call, and print(String(repeating: "*", count: 3)) prints ***. The lesson's version avoids the call by reusing the previous row.

    Complexity

    Time: O(n²). The loop runs n times, but printing row i writes i characters, and 1 + 2 + ... + n is about n²/2. The output itself has that many characters, so no solution can do better.

    Space: O(n). The only extra memory is str, which grows to n characters.

    Edge cases and common mistakes

    • Printing after the loop. That shows only the last row, a line of n stars.
    • Printing before adding the star. The first line would be empty, and the last row would be missing.
    • Declaring str inside the loop. It would reset to empty on every pass, so every line would hold a single star.
    • Using let. str += "*" changes the string, so it must be a var.
    • Off-by-one in the range. 0...n prints n + 1 rows, and 1..<n prints n - 1.

    Testing

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