About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Print Binary Numbers Pyramid Pattern

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int count = 1;

clrscr();

 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;
    }
getch();
}

Program Explanation :

We have declared some of the variables. We have declared count variable,
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 NumberValue of Count
11
20
31
40
51
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.
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 iNo of times inner Loop gets executedValues of j
111
221 2
331 2 3
441 2 3 4
below lines will decide the value of count for next iteration -
if( i % 2 == 0)
       count=1;
else
       count=0;

No comments: