C Exercises: Convert a binary number into a decimal using math function

C For Loop: Exercise-46 with Solution

Write a C program to convert a binary number into a decimal number using the math function.

visual Presentation:

Convert a binary number into a decimal using math function

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.
#include <math.h>  // Include the math functions header file.

void main()
    int n1, n; // Declare variables to store input and results.
    int dec = 0, i = 0, j, d; // Initialize variables for decimal conversion.

    printf("\n\nConvert Binary to Decimal:\n "); // Print a message.
    printf("-------------------------\n"); // Print a separator.

    printf("Input the binary number:"); // Prompt the user for input.
    scanf("%d", &n); // Read the binary number from the user.
    n1 = n; // Store the original binary number for display.

    // Loop to convert binary to decimal.
    while (n != 0)
        d = n % 10; // Get the rightmost digit of the binary number.
        dec = dec + d * pow(2, i); // Convert and accumulate the decimal value.
        n = n / 10; // Remove the rightmost digit from the binary number.
        i++; // Increment the position counter.

    // Print the result.
    printf("\nThe Binary Number: %d\nThe equivalent Decimal Number is: %d\n\n", n1, dec);

Sample Output:

Convert Binary to Decimal:                                                                                    
Input  the binary number :1010100                                                                             
The Binary Number : 1010100                                                                                   
The equivalent Decimal  Number is : 84 


Flowchart : Convert a binary number into decimal using math function.

C Programming Code Editor:

Previous: Write a program in C to find LCM of any two numbers.
Next: Write a C program to check whether a number is a Strong Number or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.