C Program to Convert Binary to Decimal.

Write a C program to convert a binary number to its decimal equivalent. 
Let's understand the processing of converting a binary number to a decimal number with one example.

Example: 
Input: binaryNum = 10101
Output: 22

Explanation:
remainder = 10101 % 10 = 1, 
decimal = 1 * 1 = 1, base = 1 * 2 = 2, 
binaryNum = 1010

remainder = 1010 % 10 = 0, 
decimal = 0 * 2 + 1 * 2 = 2, base = 2 * 2 = 4, 
binaryNum = 101

remainder = 101 % 10 = 1, 
decimal = 1 * 4 + 2 * 1 = 6, base = 4 * 2 = 8, 
binaryNum = 10

remainder = 10 % 10 = 0, 
decimal = 0 * 8 + 6 * 1 = 6, base = 8 * 2 = 16, 
binaryNum = 1

remainder = 1 % 10 = 1, 
decimal = 1 * 16 + 6 * 1 = 22, base = 16 * 2 = 32, 
binaryNum = 0

Decimal equivalent = 22

Steps-by-step Algorithm:

Step 1: Take input of a binary number from the user.
Step 2: Initialize a variable decimal to store the decimal equivalent, initially set to 0.
Step 3: Initialize a variable base to store the current place value, initially set to 1.
Step 4: Extract the rightmost digit of the binary number using the modulo operator %.
Step 5: Multiply the extracted digit by base and add it to the decimal variable.
Step 6: Divide the binary number by 10 to remove the rightmost digit.
Step 7: Update the base value by multiplying it by 2, as we are moving to the next higher place value (binary is base-2 system).
Step 8: Repeat steps 4 to 7 until the binary number becomes 0.
Step 9: The value of the decimal variable will now be the decimal equivalent of the input binary number.

C code:
//C program to convert binary to decimal number
#include <stdio.h>

int main() {

    long long binaryNum;
    int decimal = 0, base = 1, remainder;

    printf("Enter a binary number: ");
    scanf("%lld", &binaryNum);

    //converting binary to decimal
    while (binaryNum != 0) {
        remainder = binaryNum % 10;
        decimal += remainder * base;
        base *= 2;
        binaryNum /= 10;
    }

    printf("Decimal equivalent: %d\n", decimal);

    return 0;
}
Output:
Enter a binary number: 11011
Decimal equivalent: 27

Time Complexity: The time complexity of the above code is O(log N), where N is the decimal equivalent of the binary number. 

Space Complexity: The space complexity of the above code is O(1), which means it uses a constant amount of additional space that does not depend on the input.

Related articles:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS