Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to convert decimal to binary number using user define function.

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Create a long decToBin(long n) function.
  2. Inside a loop, calculate the remainder of the decimal number divided by 2: rem = n % 2.
  3. Divide the decimal number by 2 to reduce it: n = n / 2.
  4. Construct the binary number physically: binary = binary + (rem * i), then multiply the position multiplier i by 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)
ADVERTISEMENT