Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 7 0 1 0 0 1 0 1 0 1 0 0 1 0 1 0

C Code Example — Pattern Programs

ADVERTISEMENT

C Program to print Pattern 7 0 1 0 0 1 0 1 0 1 0 0 1 0 1 0

Objective

Write a C program to print an alternating 0 and 1 triangle pattern.

Algorithm / Approach

  1. Run an outer loop i from 0 to n-1.
  2. Run an inner loop j from 0 to i.
  3. Check the sum of the coordinates: if ((i + j) % 2 == 0).
  4. If the sum is even, print "0". Else, print "1".
  5. Print a newline.
main.c
#include<stdio.h>
int main( ) {
 int n,i,j;
 printf("Enter the number of rows : ");
 scanf("%d",&n);
 for(i=0; i < n; i++) {
  for(j=0; j <= i; j++) {
   if((i+j) % 2==0)
    printf("0 ");
   else
    printf("1 ");
   }
  printf("\n");
 }
 return 0;
}

Expected Output

0
1 0
0 1 0
1 0 1 0
0 1 0 1 0

Explanation of the Program

  • This pattern looks complex but relies on a very simple mathematical trick based on the grid coordinates.
  • If you treat i as the Y-axis and j as the X-axis, adding them together and checking if the sum is even or odd creates a perfect alternating checkerboard pattern.

Complexity

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