Decimal to Binary conversion

Data StructureMathematical ProblemsAlgorithms

A decimal number can also be converted into its binary form. To convert a decimal number to binary number, we need to divide the number by 2 until it reaches 0 or 1. And in each step, the remainder are stored separately to form the binary equivalent number in reverse order.

In this algorithm, we will follow the recursive approach. It will help us to solve the problem without using stack data structure. In the implementation, we know that recursion of a function will follow the internal stack. We will serve our job by using that stack.

Input and Output

Input:
Decimal number 56
Output:
Binary Equivalent: 111000

Algorithm

decToBin(decimal)

Input: Decimal numbers.

Output: Binary equivalent string.

Begin
   if decimal = 0 OR 1, then
      insert decimal into the binary string
      return
   decToBin(decimal / 2)
   insert (decimal mod 2) into the binary string.
End

Example

#include<iostream>
using namespace std;

void decToBin(int dec) {
   if(dec == 1 || dec == 0) {
      cout << dec;          //print either 0 or 1 as dec
      return;
   }

   decToBin(dec/2);    //divide the number by 2 and find decimal again
   cout << dec % 2;    //after returning print the value in reverse order
}

main() {
   int dec;
   cout<<"Enter decimal number: "; cin >> dec;
   cout << "Binary Equivalent: "; decToBin(dec);
}

Output

Enter decimal number: 56
Binary Equivalent: 111000
raja
Published on 11-Jul-2018 14:29:23
Advertisements