Write a C program to convert Binary to Decimal Numbers.

Function Main
    Declare Integer num
    Output "Enter the Binary number: "
    Input num
    Output "The decimal number is:"
    Output BinaryToDecimal(num)
End

Function BinaryToDecimal (Integer num)
    Declare Integer rem
    Declare Integer sum
    Declare Integer power
    Assign sum = 0
    Assign power = 0
    While num > 0
        Assign rem = num MOD 10
        Assign num = num / 10
        Assign sum = sum + rem * POW(2, power)
        Assign power = power + 1
    End
Return Integer sum

Function POW (Integer Base, Integer Exponent)
    Declare Integer Result
    If Exponent = 0
        Assign Result = 1
    Else
        Assign Result = Base * POW(Base, Exponent -1)
    End
Return Integer Result

#include <stdio.h>

int BinaryToDecimal(int num);
int POW(int Base, int Exponent);

int main() {
    int num;
    printf("Enter the Binary number: \n");
    scanf("%d", &num);
    printf("The Decimal number is:\n");
    printf("%d\n", BinaryToDecimal(num));
    return 0;
}

int BinaryToDecimal(int num) {
    int rem;
    int sum;
    int power;
    sum = 0;
    power = 0;
    while (num > 0) {
        rem = num % 10;
        num = (int) ((double) num / 10);
        sum = sum + rem * POW(2, power);
        power = power + 1;
    }
    return sum;
}

int POW(int Base, int Exponent) {
    int Result;
    if (Exponent == 0) {
        Result = 1;
    } else {
        Result = Base * POW(Base, Exponent - 1);
    }
    return Result;
}

Enter the Binary number: 
101
The Decimal number is:
5

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.