Pattern 5
Objective
Write a C++ program to print an alternating directional number pyramid.
Algorithm / Approach
- Use an outer loop
i. - Check if the row is even:
if(i % 2 == 0). - If even, run a loop from 1 to
ito print numbers forwards. - If odd, run a loop from
idown 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-elseblock, 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)