C Program to Convert Decimal to Binary and Vice-Versa
What is Binary Number?
The Binary Number is number which has base 2. which consists of only two numerical symbols ‘1’ and ‘0’ and each digit is referred to as a ‘Bit’.
For Example 5 in binary can be written as 0101.
What is Decimal Number?
The number which has base 10 is called a Decimal Number system.
For Example 0101=2^3*0+2^2*1+2^1*0+2^0*1=0+4+0+1=5.
There are so many ways to convert Decimal to binary and vice versa. we will see it one by one.
1. Program to Convert decimal to Binary
In this program, we will ask user to enter the number which the users want to convert it into Binary.
Decimal to Binary Conversion Algorithm:
1 Step: At first divide the number by 2 by using modulus operator ‘%’ and store the remainder in the array.
2 Step: divide that number by 2.
3 Step: Now repeat the step until the number is greater than 0.
Output:

Explanation:
Let us consider the input number as 5. At first, the value of i is 0.
1st Iteration: for(i=0;number>0;i++) i.e (i=0;5>0;0++) conition is true and a[0]=number%2=5%2=1. Therefore,number=number/2=2.5.
2nd Iteration: for(i=0;number>0;i++) i.e (i=1;2>0;1++) conition is true and a[1]=number%2=2.5%2=0. Therefore,number=2.5/2=1.25.
3rd Iteration: for(i=0;number>0;i++) i.e (i=2;1>0;2++) conition is true and a[2]=number%2=1.25%2=1. Therefore,number=number/2=0.
In this program, we have used for loop.
2. C Program to Convert Binary to Decimal
In this program, we will convert the Binary input to Decimal.
Binary to Decimal Conversion Algorithm:
1 Step: Take a Binary Input to convert into Decimal.
2 Step: Multiply each binary digit starting from last with the power of 2 i.e(2^0,2^1).
3 Step: make an addition of the multiplied digits.
4 Step: Thus the addition gives the Decimal output.
Output:

3. C program to Convert Decimal to Binary Using While loop
In this program, we have used while loop instead of for loop but the logic behind the conversion is the same.
Output:

4. Decimal to Binary Using Function
In this program, we will use the user-defined function and Bitwise AND operator to convert a decimal number into binary.
Output:

In the above program, we have used a user-defined function Decimal_to_Binary.
Post a Comment