Tuesday, 9 October 2012

How to convert binary number into decimal number in C++ using recursion

#include<iostream>

#include<conio.h>

using namespace std;

int pow(int base, int power);

int ConvertBinary(int number, int counter);
     
int main()
{
      int decimal_number = 0, binary_number = 0, temp_number = 0, remainder = 0, counter = 0;

       cout << "\n\n\t   __ Program to convert Binary number into Decimal number __";

       cout << "\n\n\n  Enter the Binary Number - ";

       cin >> binary_number;

       temp_number = binary_number;    

       decimal_number = ConvertBinary(binary_number, 0);

       cout << "\n\n  Decimal Conversion of Binary Number " << binary_number;

       cout << " (BASE 2) is -- " << decimal_number << " (BASE 10)";

       getch();

       return 0;
}

int ConvertBinary(int number, int counter)
{
       if (number == 0)
       {
              return 0;
       }
       else
       {
              return (number % 10) * pow(2, counter) + ConvertBinary(number/10, counter + 1);
             
       }
}


int pow(int base, int power)
{
       int temp = 0, result = 1;

       for (temp = 1 ; temp <= power ; temp++)
       {
              result = result * base;         
       }

       return result;

}


No comments:

Post a Comment