In this post we are going to make Decimal to Binary In C With Algorithm
Algorithm
Divide the decimal number by 2.
Store the remainder of the division as the next digit in the binary number.
Divide the quotient obtained in step 1 by 2.
Repeat steps 2 and 3 until the quotient is 0.
The binary number is the series of remainders obtained in step 2, in reverse order.
Code
#include <stdio.h>
#include <stdlib.h>
int main() {
int decimal, quotient;
char binary[100]; // Array to store the binary number
int i = 0; // Index for the binary array
printf("Enter a decimal number: ");
scanf("%d", &decimal);
quotient = decimal; // Initialize the quotient to the decimal number
while (quotient != 0) {
// Store the remainder as the next digit in the binary number
binary[i++] = quotient % 2 + '0';
quotient /= 2; // Divide the quotient by 2 and store the result
}
// Add a null terminator to the binary string
binary[i] = '\0';
printf("Binary number: ");
// Print the binary number in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%c", binary[j]);
}
return 0;
}
Output
Enter a decimal number: 38734
Binary number: 1001011101001110
Summary
This code reads a decimal number from the user and then uses a while loop to divide the number by 2 repeatedly, storing the remainders as the digits of the binary number. It then prints the binary number in reverse order.