# C Program To Convert Decimal To Binary

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

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;

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.

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.