C Program to convert binary to decimal number using user define function.
Objective
Write a C program to convert a Binary number to Decimal using a user-defined function.
Algorithm / Approach
- Create a
long binToDec(long n)function. - Inside a loop (
while n != 0), extract the last binary digit using% 10. - Multiply that digit by 2i (where
iis the current position index starting at 0). - Add it to the
decrunning total. - Chop off the last digit of the binary number (
n = n / 10) and incrementi.
main.c
#include<stdio.h>
#include<math.h>
long binToDec(long n);
int main() {
long bi;
printf("Enter a binary no. :");
scanf("%ld", &bi);
printf("BINARY : %ld \n",bi);
printf("DECIMAL: %ld",binToDec(bi));
return 0;
}
long binToDec(long n) {
int rem;
long dec = 0, i=0;
while(n != 0) {
remainder = n%10;
n = n/10;
dec = dec + (rem*pow(2,i));
++i;
}
return dec;
}
Expected Output
Enter a binary no. :11011 BINARY : 11001 DECIMAL : 27
Explanation of the Program
- To convert Binary to Decimal, you multiply each bit by 2 raised to the power of its positional index (starting from 0 on the right) and sum them up.
- Note on the provided code: the variable used to store the modulo is declared as
rem, but later the code tries to assign it toremainder. This typo will cause a compiler error.
Complexity
Time Complexity
O(log₁₀ n)
Space Complexity
O(1)
Common Mistakes
- Variable naming typos inside the function (declaring
rembut usingremainder).