The Program in C that Converts decimal no. to its binary equivalent is given below:
#include <stdio.h>
void decimal_to_binary(int n) {
int binary_num[32];
int i = 0;
while (n > 0) {
binary_num[i] = n % 2;
n = n / 2;
i++;
}
printf("The binary equivalent is: ");
for (int j = i - 1; j >= 0; j--)
printf("%d", binary_num[j]);
}
int main() {
int decimal_num;
printf("Enter a decimal number: ");
scanf("%d", &decimal_num);
decimal_to_binary(decimal_num);
return 0;
}
Output:
Enter a decimal number: 1011
The binary equivalent is: 1111110011
Pro-Tips💡
This program prompts the user to enter a decimal number, then uses a while loop to convert that decimal number to its binary equivalent.
It uses an array binary_num
to store the binary digits and a variable i
to keep track of the array index.
Inside the while loop, the program uses the modulo operator to find the remainder when the decimal number is divided by 2, and this remainder is stored in the array as the next binary digit.
The program then divides the decimal number by 2, discarding the remainder, in this way we get the next digit.
The for loop iterates from the last to the first element of array and prints the binary equivalent of the decimal number.
It is also possible to use bitwise operator >>
instead of division operator /
to get the next digit, and bitwise operator &
instead of modulus operator %
to get the remainder.
You can also use inbuilt function itoa()
to convert decimal to binary which is available in <stdlib.h> library.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.