Start learning free

LESSON 175 OF 338 · STRINGS

Print Triangle of Stars in Go

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

    GO · STRINGS

    Print Triangle Of Stars in Go, explained

    Problem overview

    The function printStars receives a positive integer n and prints n lines. Line i (counting from 1) holds i stars. For n = 5 the output is:

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

    The function prints its result and returns nothing, so there is no return value to build.

    Approach

    You could count stars separately for each line and print that many in an inner loop. A simpler observation avoids the second loop: every row is the previous row plus one star. So keep a single string for the current row, add one star to it on every pass, and print it. The first pass gives one star, the second two, and so on, which is the staircase shape.

    Another way to see the same program: row k is the star character repeated k times, and you can get there either by growing a string, as this lesson does, or by building each row afresh from a counter. The growing-string version keeps the state in one variable and needs no nested loop, which makes it the easier one to get right the first time.

    Step by step

    1. Declare str with := as the empty string. It holds the current row.
    2. Write a for loop that runs n times: i := 0, condition i < n, step i++. The variable only counts rows.
    3. In the loop, append "*" to str with +=.
    4. Still in the loop, print str with fmt.Println, which ends each call with a newline.

    The order inside the loop matters. Add the star first and print second, so the first row already has a star. If you print before adding, the first line is empty and the last line has n - 1 stars.

    The solution in Go

    func printStars(n int) {
        str := ""
        for i := 0; i < n; i++ {
            str += "*"
            fmt.Println(str)
        }
    }
    

    Language details worth knowing

    Go has only one loop keyword, for, and the three-part form init; condition; post is the counting loop you see here. The loop starts at 0 and stops before n, so it runs exactly n times. Starting at 1 and using i <= n would run the same number of times, but the version above is the convention.

    str is declared outside the loop on purpose. A variable declared inside the loop body would be created again on every pass and start empty each time, so the rows would never grow.

    Strings in Go are immutable, so str += "*" builds a new string with one more star and stores it back in str. For the sizes in this lesson that cost is irrelevant. The program prints about n²/2 characters anyway, so building each row from scratch costs the same order of work as printing it.

    fmt.Println needs the fmt package imported. It prints its argument followed by a newline, which is what puts each row on its own line. fmt.Print would leave all stars on one line.

    Edge cases and common mistakes

    • With n = 1 the output is a single line with one star.
    • With n = 0 the loop never runs and nothing is printed. The statement only asks for positive values.
    • Printing after the loop shows only the last row.
    • Declaring str inside the loop gives n lines of one star each.
    • Using single quotes, '*', makes a rune, and Go does not let you add a rune to a string with +=. Use double quotes.

    Testing

    For n = 3 the output should be:

    *
    **
    ***
    

    For n = 1 it should be a single *.

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free