WAP to convert decimal to binary number using user define function
Objective
Write a C++ program to convert a Decimal number to Binary using a function.
Algorithm / Approach
- In a loop, calculate the remainder of the number divided by 2 (
rem = n % 2). - Update the number by dividing it by 2.
- Assemble the binary number mathematically:
binary = binary + (rem * i), whereimultiplies by 10 each loop to shift digits left.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
long decToBin(long n);
int main() {
long n;
cout<<"Enter a decimal no. :";
cin>>n;
cout<<"DECIMAL: "<< n<< endl;
cout<<"BINARY : "<< 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
- Decimal to binary conversion is achieved by repeatedly dividing the number by 2 and tracking the remainders.
- By multiplying the remainder by an increasing power of 10 (1, 10, 100...) before adding it to our total, we simulate building the binary number backwards mathematically without needing arrays or strings.
Complexity
Time Complexity
O(log₂ n)
Space Complexity
O(1)