Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 6

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 6

Objective

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

Algorithm / Approach

  1. Use an outer loop i from 1 to 4.
  2. Print increasing spaces using j < i.
  3. Print descending numbers using j up to 5-i.
  4. Print the right side of the mirrored numbers using 4-i down to 1.
main.cpp
#include<iostream>
using namespace std;
int main() {
 for(int i =1; i<=4; i++) {
  for(int j =1; j< i;j++) {
   cout<<" ";
  }
  for(int j = 1; j<=5-i; j++) {
   cout<< j;
  }
  for(int k = 4-i;k>=1; k--) {
   cout<< k;
  }
  cout<< endl;
  }
 return 0;
}

Expected Output

1234321
 12321
  121
   1

Explanation of the Program

  • This is the exact opposite of the standard pyramid.
  • Instead of the spaces decreasing and the numbers increasing per row, the spaces increase (pushing the pattern inward) and the number bounds shrink (5-i), causing the pyramid to taper to a point at the bottom.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT