In the world of computers, binary numbers play a crucial role in data storage, processing, and communication. A decimal number is based on the base 10 numeral system, whereas binary numbers use the base 2 system. Converting decimal numbers to binary is one of the most fundamental operations in computer science. In this program, we will learn how to convert a decimal number to its binary equivalent using C programming.
Objective
The objective of this program is to demonstrate how to convert a given decimal number into its binary representation using simple arithmetic and logic in C. The program will repeatedly divide the number by 2 and store the remainders to generate the binary equivalent.
Program Code:
#include void decimalToBinary(int n) { int binary[32]; // Array to store binary number int i = 0; // If the number is 0, we directly print 0 as binary. if (n == 0) { printf("Binary equivalent: 0\n"); return; } // Loop to calculate binary representation while (n > 0) { binary[i] = n % 2; // Store remainder in binary array n = n / 2; // Divide the number by 2 i++; } // Print the binary number in reverse order printf("Binary equivalent: "); for (int j = i - 1; j >= 0; j--) { printf("%d", binary[j]); } printf("\n"); } int main() { int decimalNumber; // Ask the user to input a decimal number printf("Enter a decimal number: "); scanf("%d", &decimalNumber); // Call the function to convert the number decimalToBinary(decimalNumber); return 0; }
Explanation of the Program:
The program begins by declaring an integer array binary[32]
to hold the binary digits (32 bits for the maximum integer size in C). The function decimalToBinary(int n)
is responsible for the conversion process.
- The function checks if the number is 0. If it is, the binary equivalent is directly printed as 0.
- For any other positive integer, the program repeatedly divides the decimal number by 2 and stores the remainders (0 or 1) in the
binary[]
array. These remainders represent the binary digits. - Once the division process is complete, the remainders are in reverse order, so we print them in reverse to get the correct binary number.
How to Run the Program:
- Write the code in a text editor and save it as
decimal_to_binary.c
. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the program using a C compiler (e.g., GCC). Run the following command:
gcc decimal_to_binary.c -o decimal_to_binary
- Execute the program by running the following command:
./decimal_to_binary
- The program will prompt you to enter a decimal number, and it will print the binary equivalent.