C Program to Print Number Pattern with Output and Explanation
for loops; for example, use for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { printf("%d ", j); } printf("\n"); } to print numbers from 1 up to the current line number.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("%d ", j); } printf("\n"); } return 0; }
Dry Run
Let's trace the program for input n=3 to see how it prints the pattern.
Input
User enters n = 3
First outer loop iteration (i=1)
Inner loop runs j=1 to 1, prints '1 '
Print newline
Prints '\n' to move to next line
Second outer loop iteration (i=2)
Inner loop runs j=1 to 2, prints '1 2 '
Print newline
Prints '\n' to move to next line
Third outer loop iteration (i=3)
Inner loop runs j=1 to 3, prints '1 2 3 '
Print newline
Prints '\n' to finish pattern
| i (row) | j (column) | Printed Numbers |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1,2 | 1 2 |
| 3 | 1,2,3 | 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 pattern.
Step 2: Inner loop prints numbers
The inner for loop runs from 1 to the current row number, printing numbers in increasing order.
Step 3: New line after each row
After printing numbers for a row, printf("\n") moves the cursor to the next line for the next row.
Alternative Approaches
#include <stdio.h> int main() { int n; printf("Enter number of rows: "); scanf("%d", &n); for (int i = n; i >= 1; i--) { for (int j = 1; j <= i; j++) { printf("%d ", j); } printf("\n"); } return 0; }
#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("%d ", i); } 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 only a few variables and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches use nested loops with similar time complexity; differences are mainly in output style, not performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Increasing number pattern | O(n^2) | O(1) | Simple ascending patterns |
| Reverse number pattern | O(n^2) | O(1) | Descending patterns |
| Same number per row | O(n^2) | O(1) | Patterns with repeated numbers |