C program to convert a decimal number to a binary number

C program to convert a decimal number to a binary number

This C program is to convert a decimal number to a binary number.

For eg 9(DECIMAL) —>  1001(BINARY).

Logic

Take a decimal number and keep breaking it down like find remainder and quotient.

Dry Run of the Program

Take an input decimal number ‘n’. Let us say n=2

1st iteration while(n!=0)  while(2!=0)

b[i]=n%2   i.e b[0]=2%2   hence b[0]=0

n=n/2   i.e n=2/2  hence n=1

i++; ie i=1

c++ ie c=1

2nd iteration while(n!=0)  while(1!=0)

b[i]=n%2   i.e b[1]=2%2   hence b[0]=0

n=n/2   i.e n=1/2  hence n=0

i++; ie i=2

c++ ie c=2

While loop ends as n=0

Then we get into the for loop

1st iteration for(i=c-1;i>=0;i–)    i.e. for(i=1;i>=0;i–)   as c=2

print b[i] i.e b[1] = 1    print 1

2nd iteration for(i=c-1;i>=0;i–)    i.e. for(i=0;i>=0;i–)

print b[i] i.e b[0] = 0     print 1 0

For loop ends and 2’s binary number –> 1 0 (BINARY)

Program

#include<stdio.h>
void main()
{
	int b[20],n,i,c;
	printf("Enter the decimal no\n");
	scanf("%d",&n);
	i=0;
	c=0;
	while(n!=0)
	{
		b[i]=n%2;
		n=n/2;
		i++;
		c++;
	}
	printf("Binary number :-\n");
	for(i=c-1;i>=0;i--)
		printf("%d ",b[i]);
}

Output

Share Me!