Pattern 7
Objective
Write a C++ program to print a binary checkerboard right half pyramid.
Algorithm / Approach
- Use an outer loop
i. - Use an inner loop
jfrom 0 toi. - Print the result of
(i + j) % 2.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(int i = 0; i<=4; i++) {
for(int j = 0; j<=i; j++) {
cout<<(i+j)%2;
}
cout<< endl;
}
return 0;
}
Expected Output
0 1 0 0 1 0 1 0 1 0 0 1 0 1 0
Explanation of the Program
- This relies on a clever mathematical grid trick.
- If you add the row index and the column index together, the sum will alternate between even and odd across the grid. Using modulo 2 on that sum produces a perfect alternating 0 and 1 checkerboard pattern.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)