How to convert Binary to Decimal and Vice-versa in C || Type 3 || Functions || C programming
In this program, we are going to see how to Convert Binary to Decimal and Vice-versa (Type-3) in C Programming Language.

 

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int binaryToDecimal()
{
    int num;
    printf("Enter the Binary Number: ");
    scanf("%lld", &num);
    int decimal = 0, i = 0, remainder;
    while (num != 0)
    {
        remainder = num % 10;
        num /= 10;
        decimal += remainder * pow(2, i);
        ++i;
    }

    return decimal;
}

long long int decimalToBinary()
{
    long long int n;
    printf("Enter the Decimal Number: ");
    scanf("%d", &n);
    long long int binary = 0;
    int rem, i = 1, step = 1;

    while (n != 0)
    {
        rem = n % 2;
        n /= 2;
        binary += rem * i;
        i *= 10;
    }

    return binary;
}

int main()
{
    int operation;
    printf("-----Select the Operation------\n");
    printf("1. Binary to Decimal\n2. Decimal to Binary\n3. Exit\n");
    printf("Enter the corresponding number of Operation: ");
    scanf("%d", &operation);

    switch (operation)
    {
    case 1:
        printf("%d in decimal",binaryToDecimal());
        break;

    case 2:
        printf("%lld in binary",decimalToBinary());
        break;

    case 3:
        exit(0);

    default:
        printf("Wrong input");
    }

    return 0;
}

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post