This C program converts a decimal number into its binary equivalent.
Before writing the code, you must learn about binary and decimal number systems.
Program 1: C program to convert decimal to binary
#include<stdio.h> int main() { long num,rem,base=1,binary=0; printf("Enter a number: "); scanf("%ld",&num); while(num>0) { rem=num%2; binary=binary+rem*base; num=num/2; base*=10; } printf("\nBinary equivalent of the entered number is: %ld \n",binary); return 0; }
Sample Output:
Enter a number: 9
Binary equivalent of the entered number is: 1001
Program 2: C Program to convert decimal to binary using for loop
#include<stdio.h> int main() { long num,rem,base=1,binary=0; printf("Enter a number(base 10): "); scanf("%ld",&num); //decimal to binary conversion using for loop for(;num>0;num=num/2) { rem=num%2; binary=binary+rem*base; base*=10; } printf("\nBinary equivalent of the entered number is: %ld \n",binary); return 0; }
Sample output:
Enter a number(base 10): 15
Binary equivalent of the entered number is: 1111
Share your code to convert decimal to binary in the comments.