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

 

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

void binaryToDecimal()
{
    long long int num;
    printf("Enter a 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;
    }

    printf("%d in decimal",decimal);
}

void decimalToBinary()
{
    long long int binary = 0;
    int rem, i = 1, step = 1, n;
    printf("Enter a decimal number: ");
    scanf("%d", &n);

    while (n != 0)
    {
        rem = n % 2;
        n /= 2;
        binary += rem * i;
        i *= 10;
    }
    printf("%lld in binary", 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:
        binaryToDecimal();
        break;

    case 2:
        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