Pattern 9
Objective
Write a C++ program to print a right half pyramid containing sequential even numbers.
Algorithm / Approach
- Initialize an external counter
k = 1. - Use outer and inner loops to build the pyramid shape.
- Inside the inner loop, print
2 * kand then incrementk++.
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 (
iorj) to determine what to print, this pattern uses an independent, continuously growing variable (k). - By continuously incrementing
kand 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)