In this article, we will write a C program to convert a decimal number to binary with the help of an array.
The program takes an integer from the user, converts it into its equivalent binary number and prints the result on the screen.
Sample Input:
Enter a number: 27
Sample Output:
The Binary Equivalent is: 11011
Before writing the actual program, let’s first see how you get the binary equivalent of a decimal number.
To convert a decimal number to a binary number, you can follow these steps:
- Divide the decimal number by 2.
- Write down the integer quotient (the result of the division) and the remainder (either 0 or 1).
- If the quotient is greater than 0, repeat steps 1 and 2 using the quotient as the new decimal number.
- Write down the remainders in reverse order to get the binary number.
Let’s follow all these steps and write the actual program:
// C program to convert decimal // to binary using Array #include <stdio.h> int main() { int num, count = 0, arr[100]; printf("Enter a number: "); scanf("%d", &num); // Repeat until num becomes zero while(num!=0){ arr[count] = num % 2; // Remainder num = num / 2; // Quotient count++; } printf("The Binary Equivalent is: "); for(int i = 0; i < count; i++){ // Print the bits in reverse order printf("%d", arr[count-i-1]); } return 0; }
Output:
Enter a number: 27 The Binary Equivalent is: 11011
Code Explanation:
Here is a brief explanation of how the above program works:
- Declare integer variables “num”, “count” and an integer array “arr” of size 100.
- Prompt the user to enter a decimal number using the
printf()
function. - Read the input number from the user using the
scanf()
function and store it in the “num” variable. - Initialize “count” to 0.
- Use a while loop to convert the decimal number “num” into its binary equivalent using the following steps:
- Compute the remainder of “num” divided by 2 using the modulus operator (num % 2) and store it in the next index of “arr”.
- Update the value of “num” to be equal to the quotient of “num” divided by 2 using integer division (num / 2).
- Increment the value of “count” by 1.
- Repeat the above three steps until “num” becomes 0.
- Use a for loop to print the binary equivalent stored in the “arr” array in reverse order using the following steps:
- Loop from 0 to count-1.
- Access each element of the “arr” array in reverse order using the index (count-i-1).
- Print each bit using
printf()
function.
That’s how it works. Thanks for reading!