C Program To Convert Decimal To Binary

In this program, we will learn how to convert decimal to binary using C Programming language.

C Program To Convert Decimal To Binary

Decimal is a term that describes the base-10 number system. The decimal system consists of ten single digit numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols ‘0’ and ‘1’.

This program takes a decimal number as input from the user and converts it into a binary number using custom defined function. 

So, without further ado, let’s begin this tutorial.

C Program To Convert Decimal To Binary

// C Program To Convert Decimal To Binary
#include <stdio.h>
#include <math.h>
long convert(int n){
    int rem, temp = 1;
    long binary = 0;
    
    while (n != 0){
        rem = n %2;
        n = n / 2;
        binary = binary + rem * temp;
        temp = temp * 10;
    }
    return binary;
}

int main(){
    int num;
    
    // Asking for Input
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    printf("%d in Decimal = %d in Binary", num, convert(num));
    return 0;
}

Output

Enter a decimal number: 18
18 in Decimal = 10010 in Binary

How Does This Program Work ?

long convert(int n){
    int rem, temp = 1;
    long binary = 0;
    
    while (n != 0){
        rem = n %2;
        n = n / 2;
        binary = binary + rem * temp;
        temp = temp * 10;
    }
    return binary;
}

In the program, we have defined a custom function named convert which converts decimal system to binary number system.

Suppose the user enters 18 as an input, then 18 != 0, so the function continues the following steps.

n != 0temp  remn = n/2     binary += rem * temp
18 != 0  18 % 2 = 0 18 / 2 =  90 + (0 * 1) = 0
9 != 0109 % 2 = 19 / 2 = 40 + (1 * 10) = 10
4 != 0100 4 % 2 = 04 / 2 = 210 + (0 * 100) = 10
2 != 01000    2 % 2 = 02 / 2 = 110 + (0 * 1000) =10
1 != 0100001 % 2 = 11 / 2 = 010 + (1 * 10000) =10010
0 != 0
Decimal To Binary

Hence, we get (18)10 = (10010)2

   printf("%d in Decimal = %d in Binary", num, convert(num));

Then, we call this function in the main function to print the binary number obtained after conversion.

Conclusion

I hope after going through this post, you understand how to convert decimal to binary using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *