Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 7

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 7

Objective

Write a C++ program to print a binary checkerboard right half pyramid.

Algorithm / Approach

  1. Use an outer loop i.
  2. Use an inner loop j from 0 to i.
  3. 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)
ADVERTISEMENT