Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 4

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 4

Objective

Write a C++ program to print a centered number palindrome pyramid.

Algorithm / Approach

  1. Use an outer loop i for rows.
  2. Use a loop to print decreasing spaces.
  3. Use a loop k from 1 up to i to print the ascending left side of the numbers.
  4. Use a loop m from i-1 down 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)
ADVERTISEMENT