In this article, we will learn to write a C program to convert a decimal number into a binary number. The decimal number system uses ten digits from 0 to 9 to represent numbers and the binary number system is a base-2 number system that uses only 0 and 1 to represent numbers.
Algorithm to Convert Decimal Numbers to Binary in C
- Find the remainder by taking the modulus of the given number with 2.
- Store the remainder as a binary digit in an array.
- Update the number by dividing it by 2.
- Repeat these steps till the number is greater than zero.
C Program to Convert Decimal Numbers to Binary
C
// C Program to Convert Decimal Numbers to Binary #include <stdio.h> // function to convert decimal to binary void decToBinary( int n)
{ // array to store binary number
int binaryNum[1000];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for ( int j = i - 1; j >= 0; j--)
printf ( "%d" , binaryNum[j]);
} // Driver program to test above function int main()
{ int n = 17;
decToBinary(n);
return 0;
} |
Output
10001
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
Please refer complete article on Program for Decimal to Binary Conversion for more details!
Article Tags :
Recommended Articles