C Program to Print Right Triangle Pattern
for loops in C where the outer loop controls rows and the inner loop prints stars, like for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) printf("*"); printf("\n"); } to print a right triangle pattern.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n; printf("Enter number of rows: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { printf("*"); } printf("\n"); } return 0; }
Dry Run
Let's trace the program with input 3 to see how it prints the right triangle.
Input
User enters n = 3
First outer loop iteration (i=1)
Inner loop runs j=1 to 1, prints '*' once, then newline
Second outer loop iteration (i=2)
Inner loop runs j=1 to 2, prints '**', then newline
Third outer loop iteration (i=3)
Inner loop runs j=1 to 3, prints '***', then newline
End
All rows printed, program ends
| i (row) | Stars printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing one row of the triangle.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number i, 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 to start the next row.
Alternative Approaches
#include <stdio.h> int main() { int n, i = 1, j; printf("Enter number of rows: "); scanf("%d", &n); while (i <= n) { j = 1; while (j <= i) { printf("*"); j++; } printf("\n"); i++; } return 0; }
#include <stdio.h> void printStars(int count) { if (count == 0) return; printf("*"); printStars(count - 1); } void printTriangle(int row, int n) { if (row > n) return; printStars(row); printf("\n"); printTriangle(row + 1, n); } int main() { int n; printf("Enter number of rows: "); scanf("%d", &n); printTriangle(1, n); return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times and the inner loop runs up to n times in the last iteration, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The program uses a fixed amount of extra space for variables and does not allocate additional memory proportional to input size, so O(1).
Which Approach is Fastest?
The nested for loop approach is straightforward and efficient for this problem; recursion adds overhead and is less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and efficient for beginners |
| Nested while loops | O(n^2) | O(1) | Similar to for loops, slightly more verbose |
| Recursion | O(n^2) | O(n) | Elegant but uses more stack space and complex |