Convert Decimal to Binary in C
Last Updated :
18 Jul, 2023
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
#include <stdio.h>
void decToBinary( int n)
{
int binaryNum[1000];
int i = 0;
while (n > 0) {
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
for ( int j = i - 1; j >= 0; j--)
printf ( "%d" , binaryNum[j]);
}
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
|
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
Please refer complete article on Program for Decimal to Binary Conversion for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...