Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 9

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 9

Objective

Write a C++ program to print a right half pyramid containing sequential even numbers.

Algorithm / Approach

  1. Initialize an external counter k = 1.
  2. Use outer and inner loops to build the pyramid shape.
  3. Inside the inner loop, print 2 * k and then increment k++.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int k = 1;
 for(int i = 1; i< 4; i++) {
  for(int j = 1; j<=i; j++) {
   cout<< 2*k<<" ";
   k++;
  }
  cout<< endl;
 }
return 0;
}

Expected Output

2
4 6
8 10 12

Explanation of the Program

  • Unlike patterns that use the loop variables (i or j) to determine what to print, this pattern uses an independent, continuously growing variable (k).
  • By continuously incrementing k and multiplying it by 2, we generate a continuous stream of even numbers (2, 4, 6, 8, 10...) that wraps around to the next row.

Complexity

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