C++ Program to Print Inverted Pyramid Pattern
for loops where the outer loop controls the rows and the inner loops print spaces and stars; for example, use for (int i = n; i >= 1; i--) to print decreasing stars each row.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int n; cout << "Enter number of rows: "; cin >> n; for (int i = n; i >= 1; i--) { for (int space = 0; space < n - i; space++) cout << ' '; for (int star = 0; star < i; star++) cout << '*'; cout << '\n'; } return 0; }
Dry Run
Let's trace the program with input 3 through the code
Input
User enters n = 3
First row (i=3)
Print 0 spaces, then 3 stars: ***
Second row (i=2)
Print 1 space, then 2 stars: **
Third row (i=1)
Print 2 spaces, then 1 star: *
| Row (i) | Spaces (n - i) | Stars (i) | Output line |
|---|---|---|---|
| 3 | 0 | 3 | *** |
| 2 | 1 | 2 | ** |
| 1 | 2 | 1 | * |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from n down to 1, controlling how many stars to print each line.
Step 2: Print spaces before stars
The first inner loop prints spaces to shift stars right, using n - i spaces to align the pyramid.
Step 3: Print stars
The second inner loop prints stars equal to the current row number i, decreasing each line to form the inverted pyramid.
Alternative Approaches
#include <iostream> using namespace std; int main() { int n; cout << "Enter number of rows: "; cin >> n; int i = n; while (i >= 1) { int space = 0; while (space < n - i) { cout << ' '; space++; } int star = 0; while (star < i) { cout << '*'; star++; } cout << '\n'; i--; } return 0; }
#include <iostream> using namespace std; int main() { int n; cout << "Enter number of rows: "; cin >> n; for (int i = n; i >= 1; i--) { for (int star = 0; star < i; star++) cout << '*'; cout << '\n'; } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loops run up to n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used for counting; no extra space proportional to input size is needed, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using for loops is concise and clear, while while loops are more verbose but equally efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Clear and concise code |
| While loops | O(n^2) | O(1) | Beginners learning loop control |
| No spaces (left-aligned) | O(n^2) | O(1) | Simpler output without alignment |