Start learning free

LESSON 174 OF 347 · STRINGS

Print a Triangle of Stars in C#

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

    C# · STRINGS

    Print Triangle Of Stars in C#, explained

    Problem overview

    The method PrintStars takes a positive integer n and prints n lines. Line number i (counting from 1) contains exactly i stars. It prints its output and returns nothing, which is why the return type is void.

    For n = 5 the output is:

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

    Approach: grow one row at a time

    Every row is the previous row with one more star on the end. So you don't need to compute how many stars to print on each line: keep a string for the current row, add a star to it, print it, and repeat n times. The loop's counter only decides how many rows to print.

    Tracing n = 3: str starts empty. Iteration 0 makes it "*" and prints it. Iteration 1 makes it "**" and prints it. Iteration 2 makes it "***" and prints it. After that the loop condition fails and the method ends.

    Another way to think about it is that the string remembers the work of the previous iterations, so each iteration only does a small amount of new work: one extra character.

    Step by step

    1. Start with an empty row. string str = ""; holds the current row. Before the first iteration it contains no stars.
    2. Loop once per row. for (int i = 0; i < n; i++) runs exactly n times. The counter starts at 0 here, but its value is never used inside the loop; it just counts rows.
    3. Add a star. str += "*"; appends a star at the start of each iteration, so the first row has one star, the second two, and so on.
    4. Print the row. Console.WriteLine(str); prints the text and ends the line, so every row lands on its own line. It has to sit inside the loop and after the star is added. Printing after the loop would show only the last row.

    The solution in C#

    class Solution {
        public void PrintStars(int n) {
            string str = "";
            for (int i = 0; i < n; i++) {
                str += "*";
                Console.WriteLine(str);
            }
        }
    }
    

    A few C# notes:

    • WriteLine versus Write. Console.WriteLine adds a line break after the text. Console.Write doesn't, so using it here would put all the stars on one line.
    • += on a string. Strings are immutable, so str += "*" creates a new string and assigns it to str. For a few dozen rows that is perfectly fine.
    • void methods. The method produces its result through the console, so there is no return statement.
    • A shortcut that exists. new string('*', i) builds a string of i stars directly, but this lesson builds the row by hand to practise loops and string appends.

    Complexity

    The loop runs n times, and row i has i characters, so the program builds and prints about 1 + 2 + ... + n characters in total. That is roughly n²/2, so the time is O(n²). This is unavoidable here, because the output itself contains that many characters. The extra memory is the current row, O(n).

    Edge cases and common mistakes

    • n = 1. Prints a single line with one star.
    • Starting the counter at 1 with i < n. That prints only n - 1 rows. Starting at 0 with i < n, or at 1 with i <= n, gives n rows.
    • Printing before adding the star. The first row would be empty and the last row would have n - 1 stars.
    • Declaring str inside the loop. The string would be reset on every iteration, so every row would have a single star.
    • Using Console.Write. All the stars would end up on a single line.

    Testing

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