Problem Statement
In this program we will code a basic program to convert a decimal number to a binary number. Decimal numbers ranges from 0 to 9, like 342, 456,23456 are all decimal numbers. Binary numbers are the numbers that are represented by 0’s and 1’s. Like 2 in binary form is equivalent to ‘0010’.
Code
#include <stdio.h>
void dectobin(int num)
{
int temp, i;
temp=num;
int a[10];
for(i=0;num>0;i++)
{
a[i]=num%2;
num=num/2;
}
printf("\nBinary form of %d : ",temp);
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
}
int main()
{
int n;
printf("Enter the number : ");
scanf("%d", &n);
dectobin(n);
return 0;
}
Output
Enter the number : 10
Binary form of 10 : 1010
Explanation
In this problem we have to convert a decimal number to the binary number. In the above code a[i]=num%2; // finding and storing the remainder at i-th index of an array.
num=num/2; // dividing the number by 2
We will repeat above process till our number is greater than 0.