Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to convert binary to decimal number using user define function.

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Create a long binToDec(long n) function.
  2. Inside a loop (while n != 0), extract the last binary digit using % 10.
  3. Multiply that digit by 2i (where i is the current position index starting at 0).
  4. Add it to the dec running total.
  5. Chop off the last digit of the binary number (n = n / 10) and increment i.
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 to remainder. 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 rem but using remainder).
ADVERTISEMENT