easy
1 views
Pattern Printing – Half Pyramid Numbers
Print a half pyramid pattern using numbers from 1 to N where each row contains consecutive numbers starting from 1
Understand the Problem
Problem Statement
The number of rows N is passed as the input. The program must print the half pyramid using the numbers from 1 to N.
Constraints
- 2 ≤ N ≤ 100
- N must be a positive integer
- Each row must start with 1
- Numbers in each row must be separated by a single space
- Each row should have one more number than the previous row
Examples
Example 1
Input
5Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Explanation
For N=5, we print 5 rows. Row 1 has number 1, row 2 has numbers 1-2, row 3 has numbers 1-3, and so on until row 5 which has numbers 1-5.
Example 2
Input
3Output
1
1 2
1 2 3Explanation
For N=3, we print 3 rows. Row 1 has number 1, row 2 has numbers 1-2, and row 3 has numbers 1-3, forming a half pyramid pattern.
Solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}Time:O(N²) - We have nested loops where outer loop runs N times and inner loop runs up to N times in the worst case
Space:O(1) - We only use a constant amount of extra space for variables
Approach:
The C solution uses nested for loops:
- Read integer N using scanf
- Outer loop (i) controls the rows from 1 to N
- Inner loop (j) prints numbers from 1 to current row number i
- Each number is followed by a space
- After each row, print a newline character
The nested loop structure ensures we print exactly the right pattern with proper spacing.
Visual Explanation
Loading diagram...