-5
#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
long int d2b(int);
static long int binary=0;
static int i=0;
long int d2b(int num)
{
    if(num!=0)
    {
        binary=binary+pow(10,i)*(num%2);
        d2b(num/2);
        i++;
    }
    return(binary);
}

int main()
{
    int num;
    long int binary_ans=0;
    cout<<"Enter the number.";
    cin>>num;
    binary_ans=d2b(num);
    cout<<"Ans = "<<binary_ans;
    getch();
    return(0);
}

I am using Dev C++ compiler and this code doesnt seem to work. Can somebody please run this code on their compilers and give me a feedback. Also if the code seems incorrect to you, please tell me the reason why you think so.

3 Answers3

4

A correct implementation with neither static variables nor globals (both are just plain evil, try to avoid them at any cost) that gives you the desired output can be something as simple as

#include <iostream>

long int d2b(int x)
{
  return x ? (x%2 + 10*d2b(x/2)) : 0;
}

int main()
{
  std::cout << "enter a number:" << std::endl;
  int input;
  std::cin >> input;
  long int binary = d2b(input);
  std::cout << "ans = " << binary << std::endl;
}

Take note that, as we're using int to store our binary representation, the whole thing breaks for any input > 524287.

This of course assumes your integer is 64bit. The largest number you can write using only 0 and 1 is int x = 1111111111111111111, which when you interpret it as binary translates to 524287.

For 32bit and even 16bit integers this range is significantly lower.

Also have a look at: Are global variables bad?

Lanting
  • 3,060
  • 12
  • 28
  • 1
    +1. While `d2b()` isn't what I'd call *self-explanatory* but getting rid of globals is a huge improvement nonetheless. – TobiMcNamobi Jul 07 '14 at 10:57
1

Obviously i++ must be done before the recursion takes place.

#include<iostream>
#include<conio.h>
#include<math.h>

using namespace std;

long int d2b(int);
static long int binary=0;
static int i=0;

long int d2b(int num)
{
    if(num!=0)
    {
        binary=binary+pow(10,i)*(num%2);
        i++;
        d2b(num/2);
    }
    return(binary);
}

int main()
{
    int num;
    long int binary_ans=0;
    cout<<"Enter the number.";
    cin>>num;
    binary_ans=d2b(num);
    cout<<"Ans = "<<binary_ans;
    _getch();
    return(0);
}

Get used to debugging your code!

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
0

As mentioned earlier, you can use it also in this manner:

#include<iostream>
#include<math.h>
using namespace std;
string d2b(int);
static string binary;
string d2b(int num)
{
    if(num!=0)
    {
        binary= to_string(num%2) + binary;
        d2b(num/2);
    }
    return(binary);
}

int main()
{
    int num;
    string binary_ans="";
    cout<<"Enter the number.";
    cin>>num;
    binary_ans=d2b(num);
    cout<<"Ans = "<<binary_ans;
    getch();
    return(0);
}
Shashish Chandra
  • 489
  • 2
  • 5
  • 20