C# Program to Print Star Pattern
for loops; for example, for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } prints a right-angled triangle of stars.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int rows = 5; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } } }
Dry Run
Let's trace the program with rows = 3 to see how stars print.
Start outer loop with i=1
Inner loop runs j=1 to 1, prints '*' once, then moves to new line.
Outer loop i=2
Inner loop runs j=1 to 2, prints '**', then moves to new line.
Outer loop i=3
Inner loop runs j=1 to 3, prints '***', then moves to new line.
| i (row) | j (star count) | Output line |
|---|---|---|
| 1 | 1 | * |
| 2 | 2 | ** |
| 3 | 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the number of rows, deciding how many lines to print.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number, printing stars on the same line.
Step 3: Move to next line
After printing stars for a row, Console.WriteLine() moves the cursor to the next line for the next row.
Alternative Approaches
using System; class Program { static void Main() { int rows = 5; int i = 1; while (i <= rows) { int j = 1; while (j <= i) { Console.Write("*"); j++; } Console.WriteLine(); i++; } } }
using System; class Program { static void Main() { int rows = 5; for (int i = 1; i <= rows; i++) { Console.WriteLine(new string('*', i)); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Using new string('*', i) is faster and cleaner than nested loops because it avoids manual printing inside loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Learning loops and control flow |
| While loops | O(n^2) | O(1) | Alternative loop syntax |
| String constructor | O(n^2) | O(1) | Cleaner and concise code |