Pattern 4
Objective
Write a C++ program to print a centered number palindrome pyramid.
Algorithm / Approach
- Use an outer loop
ifor rows. - Use a loop to print decreasing spaces.
- Use a loop
kfrom 1 up toito print the ascending left side of the numbers. - Use a loop
mfromi-1down to 1 to print the descending right side of the numbers.
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<< k;
}
for(int m = i-1; m>=1;m--) {
cout<< m;
}
cout<< endl;
}
return 0;
}
Expected Output
1 121 12321 1234321
Explanation of the Program
- This pattern combines spaces, ascending numbers, and descending numbers to create a symmetrical triangle.
- By splitting the numbers into two separate loops (one counting up, one counting down), we can easily create the mirrored palindrome effect.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)