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
- Run an outer loop
ifrom 0 ton-1. - Run an inner loop
jfrom 0 toi. - Check the sum of the coordinates:
if ((i + j) % 2 == 0). - If the sum is even, print "0". Else, print "1".
- 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
ias the Y-axis andjas 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)