A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

C program to convert the given binary number into decimal/

C program to convert the given binary number into decimal

Problem Description

This C language program converts a given binary number to decimal number. Binary numbers are the one which contains only 0 and 1. The program flow is as follows:
1. Take a binary number as input.
2. Starting from the last digit, multiply each digits of the binary number with the powers of 2 respectively(starting with 0).
3. Add all the multiplied digits.
4. The total sum gives the decimal number.

C program to convert the given binary number into decimal - Source code

/* C program to convert the given binary number into decimal */
#include <stdio.h>
#include <math.h>
int binaryToDecimal(long binary_num)
{
int decimal_num = 0, i = 0, remainder;
while (binary_num!=0)
{
remainder = binary_num % 10;
binary_num = binary_num / 10;
decimal_num = decimal_num + remainder*pow(2,i);
i++;
}
return decimal_num;
}
int main()
{
long binary_num;
printf("Enter a binary number: ");
scanf("%ld", &binary_num);
printf("Equivalent decimal number is: %d", binaryToDecimal(binary_num));
return 0;
}

Program Output

Case 1:
Enter a binary number: 10001001
Equivalent decimal number is: 137
Case 2:
Enter a binary number: 10001010
Equivalent decimal number is: 138

Program Explanation

1. A separate function binaryToDecimal is created to convert the given binary number to decimal.
2. Accept a binary number and store it in the variable binary_num.
3. Call the function binaryToDecimal function with one parameter binary_num from inside the printf statement.
4. Inside the user defined function, initialize the variable decimal_num and variable i to 0.
5. Obtain the remainder of the binary number using the modulus operator (%). Store the remainder in the variable remainder. Divide the decimal number by 10 to cut off the last digit.
6. Multiply remainder with the 2^i and add it to the decimal_num variable.
7. Increment the variable i by 1.
8. Repeat the steps 5, 6 and 7 until the binary_num value becomes 0.
9. Print the variable decimal_num as output.
10. Here note that it is necessary to include math.h header file as we are using the library function pow.