C Program to Print Binary Numbers Pyramid Pattern
Problem Statement : Generate Following Pattern of Pyramid
1 2 3 4 5 6 7 |
1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<stdio.h> int main() { int i, j; int count = 1; for (i = 1; i <= 4; i++) { printf("\n"); for (j = 1; j <= i; j++) { printf("%d", count % 2); count++; } if (i % 2 == 0) count = 1; else count = 0; } return(0); } |
Program Explanation :
We have declared some of the variables. We have declared count variable,
1 |
int count = 1; |
First and Third Line is Starting with 1 , while 2nd and 4th Line is starting with 0, So for first and third line count will be 1 and for even line number count will be equal to 0.
Line Number | Value of Count |
---|---|
1 | 1 |
2 | 0 |
3 | 1 |
4 | 0 |
5 | 1 |
Outer for loop will decide the line. In this pyramid we need to print 5 lines so we have for loop which can execute 5 times.
1 2 3 |
for(i=1;i<=5;i++) { printf("\n"); |
As each iteration of for loop is new line we need to print newline character on each line
below table explains how many times inner loop is executed -
Value of i | No of times inner Loop gets executed | Values of j |
---|---|---|
1 | 1 | 1 |
2 | 2 | 1 2 |
3 | 3 | 1 2 3 |
4 | 4 | 1 2 3 4 |
below lines will decide the value of count for next iteration -
1 2 3 4 |
if( i % 2 == 0) count=1; else count=0; |