How does a C program to convert binary number to decimal work?

 Courtesy: Programiz.com


In the program, we have included the header file math.h to perform mathematical operations in the program.

We ask the user to enter a binary number and pass it to the convert() function to convert it decimal.

Suppose n = 1101. Let's see how the while loop in the convert() function works.

n != 0rem = n % 10n /= 10idec += rem * pow(2, i)
1101 != 01101 % 10 = 11101 / 10 = 11000 + 1 * pow (2, 0) = 1
110 != 0110 % 10 = 0110 / 10 = 1111 + 0 * pow (2, 1) = 1
10 != 011 % 10 = 111 /10 = 121 + 1 * pow (2, 2) = 5
1 != 01 % 10 = 11 / 10 = 035 + 1 * pow (2, 3) = 13
0 != 0---Loop terminates

So, 1101 in binary is 13 in decimal.

Comments

Popular posts from this blog

C program to read and display book information using structure

Count positive, negative and zero values in an array

Maximum value from array