Practice › Basics
Star Pyramid
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print a centred pyramid of * with n rows. Row i (1-based) has n - i spaces followed by 2i - 1 stars. Do not print spaces after the stars.
Input
A single integer n.
Output
The pyramid, n lines.
Constraints
- 1 ≤ n ≤ 100
Example for n = 3:
* *** *****
Example 1
Input
3
Output
* *** *****
Example 2
Input
1
Output
*
Hints
- Row i needs n − i leading spaces.
- Then 2i − 1 stars, and nothing after them.
Approach
For each row i from 1 to n, print n - i spaces followed by 2i - 1 stars. Pattern problems are all about finding the formula for "how many of each character on row i" — write the counts for n = 3 on paper first.
Complexity: O(n²) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cout << string(n - i, ' ') << string(2 * i - 1, '*') << "\n";
return 0;
}Python solution
n = int(input())
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) sb.append(" ".repeat(n - i)).append("*".repeat(2 * i - 1)).append('\n');
System.out.print(sb);
}
}