C Program to convert decimal to binary number using user define function.
Objective
Write a C program to convert a Decimal number to Binary using a user-defined function.
Algorithm / Approach
- Create a
long decToBin(long n)function. - Inside a loop, calculate the remainder of the decimal number divided by 2:
rem = n % 2. - Divide the decimal number by 2 to reduce it:
n = n / 2. - Construct the binary number physically:
binary = binary + (rem * i), then multiply the position multiplieriby 10.
main.c
#include<stdio.h>
#include<math.h>
long decToBin(long n);
int main() {
long n;
printf("Enter a decimal no. :");
scanf("%ld", &n);
printf("DECIMAL: %ld", n);
printf("BINARY : %ld",decToBin(n));
return 0;
}
long decToBin(long n) {
int rem;
long binary = 0, i = 1;
while(n != 0) {
rem = n%2;
n = n/2;
binary= binary + (rem*i);
i = i*10;
}
return binary;
}
Expected Output
Enter a decimal no. : 27 DECIMAL : 27 BINARY : 11001
Explanation of the Program
- The standard algorithm to convert Decimal to Binary is to repeatedly divide the number by 2 and record the remainders (which will always be 1 or 0).
- Because we want the remainders to visually print in reverse order to form a single integer, we multiply them by expanding powers of 10 (1, 10, 100) before adding them to our binary total variable.
Complexity
Time Complexity
O(log₂ n)
Space Complexity
O(1)