C Program to Convert Binary to Decimal Number Using User Defined Function

Question: write a program in C language to read a binary number from a user and convert it to decimal number using a user defined function.

C Source Code: Binary to Decimal Conversion User Defined Function


#include<stdio.h>

/* Function Prototype */
long int binaryToDecimal(long int num);

/* Main Function */
int main()
{
	 long int binary, decimal;
	 printf("Enter valid binary number: ");
	 scanf("%ld", &binary);
	 decimal = binaryToDecimal(binary);
	 printf("Binary (%ld) = Decimal (%ld)", binary, decimal);
	 return(0);
}

/* Function Definition */
long int binaryToDecimal(long int num)
{
    long int decimal=0, base=1, rem;
    
    while(num!=0)
    {
        rem = num%10;
        decimal = decimal + base*rem;
        base = base * 2;
        num = num/10;
    }
    return decimal;
}

Output of above program :

Enter valid binary number: 1011010111
Binary (1011010111) = Decimal (727)

Note: ↲ indicates enter is pressed.