Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 5

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 5

Objective

Write a C++ program to print an alternating directional number pyramid.

Algorithm / Approach

  1. Use an outer loop i.
  2. Check if the row is even: if(i % 2 == 0).
  3. If even, run a loop from 1 to i to print numbers forwards.
  4. If odd, run a loop from i down to 1 to print numbers backwards.
main.cpp
#include<iostream>
using namespace std;
int main() {
 for(int i = 1; i<=5; i++) {
  if(i%2==0){
   for(int j = 1; j<=i; j++) {
    cout<< j;
   }
  }
  else {
   for(int j = i; j>=1; j--) {
    cout<< j;
   }
  }
 cout<< endl;
 }
return 0;
}

Expected Output

1
21
123
4321
12345

Explanation of the Program

  • This is a complex pattern that changes its printing direction based on the row number.
  • By wrapping our inner loops in an if-else block, we can conditionally choose whether to count up or count down depending on whether the current row index is even or odd.

Complexity

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