C# Program to Print Number Pattern
for loops like for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { Console.Write(j + " "); } Console.WriteLine(); } to print numbers in increasing order per line.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int n = 5; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { Console.Write(j + " "); } Console.WriteLine(); } } }
Dry Run
Let's trace the program for n=3 to see how it prints the pattern.
Start outer loop with i=1
Inner loop runs j=1 to 1, prints '1 '
Print newline after inner loop
Output so far: 1
Outer loop i=2
Inner loop j=1 to 2, prints '1 2 '
Print newline
Output so far: 1 1 2
Outer loop i=3
Inner loop j=1 to 3, prints '1 2 3 '
Print newline
Final output: 1 1 2 1 2 3
| i (row) | j (column) | Printed Numbers |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1-2 | 1 2 |
| 3 | 1-3 | 1 2 3 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration represents a new line in the pattern.
Step 2: Inner loop prints numbers
The inner for loop prints numbers from 1 up to the current row number, creating the pattern.
Step 3: New line after each row
After printing numbers for a row, Console.WriteLine() moves to the next line for the next row.
Alternative Approaches
using System; class Program { static void Main() { int n = 5; int i = 1; while (i <= n) { int j = 1; while (j <= i) { Console.Write(j + " "); j++; } Console.WriteLine(); i++; } } }
using System; class Program { static void Main() { int n = 5; for (int i = n; i >= 1; i--) { for (int j = 1; j <= i; j++) { Console.Write(j + " "); } Console.WriteLine(); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops run approximately n*(n+1)/2 times, which is O(n^2), because for each row i, the inner loop runs i times.
Space Complexity
The program uses constant extra space, only variables for counters, so O(1) space.
Which Approach is Fastest?
Using for loops is generally faster and clearer than while loops for counting patterns; reversing the pattern changes output but not complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and clear pattern printing |
| Nested while loops | O(n^2) | O(1) | Same complexity, less concise |
| Reverse pattern with for loops | O(n^2) | O(1) | Printing pattern in reverse order |