Pattern 2
Objective
Write a C++ program to print a left half pyramid using stars and spaces.
Algorithm / Approach
- Use an outer loop
ifrom 1 to 5. - Use a first inner loop
jfrom 5 down toito print spaces. - Use a second inner loop
kfrom 1 toito print stars. - Print a newline.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(int i = 1; i<=5; i++) {
for(int j = 5; j>=i; j--) {
cout<<" ";
}
for(int k = 1; k<=i; k++) {
cout<<"* ";
}
cout<< endl;
}
return 0;
}
Expected Output
*
* *
* * *
* * * *
* * * * *
Explanation of the Program
- To push characters to the right side of the screen, we must explicitly print blank spaces before we print the stars.
- Notice how the space loop counts backward from 5 down to
i. This creates an inverse relationship: as the row number increases, the number of spaces decreases, allowing the stars to gradually take up more room.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)