C Program to Print Star Pattern - Simple Example
for loops; for example, for(int i=1; i<=5; i++){ for(int j=1; j<=i; j++){ printf("*"); } printf("\n"); } prints a right-angled triangle of stars.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int rows = 5; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printf("*"); } printf("\n"); } return 0; }
Dry Run
Let's trace printing 3 rows of stars through the code.
Start outer loop with i=1
Inner loop runs j=1 to 1, prints '*' once, then newline.
Outer loop i=2
Inner loop runs j=1 to 2, prints '**', then newline.
Outer loop i=3
Inner loop runs j=1 to 3, prints '***', then newline.
| i (row) | j (star count) | Output this row |
|---|---|---|
| 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 that many stars.
Step 3: Newline after each row
After printing stars for a row, printf("\n") moves the cursor to the next line.
Alternative Approaches
#include <stdio.h> int main() { int rows = 5, i = 1; while (i <= rows) { int j = 1; while (j <= i) { printf("*"); j++; } printf("\n"); i++; } return 0; }
#include <stdio.h> int main() { int rows = 5; for (int i = rows; i >= 1; i--) { for (int j = 1; j <= i; j++) { printf("*"); } printf("\n"); } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops: 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 for variables, so space complexity is O(1).
Which Approach is Fastest?
All approaches use nested loops with similar time complexity; choice depends on readability and pattern style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Standard star patterns |
| While loops | O(n^2) | O(1) | Beginners preferring while syntax |
| Inverted pattern | O(n^2) | O(1) | Different star shapes |