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

Courtesy: Programiz.com 


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

n != 0rem = n % 2n /= 2ibin += rem * ii * = 10
13 != 013 % 2 = 113 / 2 = 610 + 1 * 1 = 11 * 10 = 10
6 != 06 % 2 = 06 / 2 = 3101 + 0 * 10 = 110 * 10 = 100
3 != 03 % 2 = 13 / 2 = 11001 + 1 * 100 = 101100 * 10 = 1000
1 != 01 % 2 = 11 / 2 = 01000101 + 1 * 1000 = 11011000 * 10 = 10000
0 != 0---Loop terminates

Thus, 13 in decimal is 1101 in binary.

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