easy
0 views
Pattern Printing – Half Pyramid Using Asterisk
Print a half pyramid pattern using asterisks (*) with N rows, where each row contains increasing number of asterisks separated by spaces.
Understand the Problem
Problem Statement
The number of rows N is passed as the input. The program must print the half pyramid using asterisk *.
Constraints
- 2 ≤ N ≤ 100
- Each row should contain asterisks separated by single spaces
- No trailing spaces at the end of lines
Examples
Example 1
Input
5Output
*
* *
* * *
* * * *
* * * * *Explanation
For N=5, we print 5 rows. Row 1 has 1 asterisk, row 2 has 2 asterisks, and so on until row 5 which has 5 asterisks. Each asterisk is separated by a single space.
Example 2
Input
3Output
*
* *
* * *Explanation
For N=3, we print 3 rows. Row 1 has 1 asterisk, row 2 has 2 asterisks, and row 3 has 3 asterisks, each separated by single spaces.
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("*");
if (j < i) {
printf(" ");
}
}
printf("\n");
}
return 0;
}Time:O(N²)
Space:O(1)
Approach:
Step-by-step explanation:
- Read the input N using scanf
- Outer loop (i): iterates from 1 to N, representing each row
- Inner loop (j): for each row i, prints i asterisks
- After each asterisk (except the last one in a row), print a space
- After completing each row, print a newline character
- Time complexity: O(N²) - nested loops
- Space complexity: O(1) - only using a few integer variables
Visual Explanation
Loading diagram...