Convert natural number to binary recursively

5

How can I make this function into a recursive function? I was able to do it iteratively this way:

#include <iostream>
using namespace std;

int main (){
    int n,pot,bin;

    cout << endl << "  Digite o Numero: ";
    cin >> n;
    pot = 1;
    bin = 0;
    while (n > 0){
        bin += (n % 2)* pot;
        pot *= 10;
        n = n/2;
    }
    cout << "  " << "Result: " << bin;
    cin.get();
    return 0;
}
    
asked by anonymous 10.02.2015 / 16:20

2 answers

4

If you just want to make the display of each digit you can use this:

#include <iostream>
#include <stdio.h>
using namespace std;
void ConvertToBinary(int n);
int main() {
    ConvertToBinary(11);
    return 0;
}
void ConvertToBinary(int n)
{
    if (n / 2 != 0) {
        ConvertToBinary(n / 2);
    }
    printf("%d", n % 2);
}

View on ideone
Adapted from this response

    
10.02.2015 / 17:06
4

You must set a limit for the function. In this case the limit is when the number to be divided by zero or less. You can do the following:

int funcao(int n, int pot, int bin) {
  bin += (n % 2)* pot;
  n = n/2;
  pot = pot *10;
  if (n <= 0) {
    return bin;
  }
  bin = funcao(n, pot, bin);
}

int main() {
  int n,pot,bin;

  cout << endl << "  Digite o Numero: ";
  cin >> n;
  pot = 1;
  bin = 0;
  bin = funcao(n, pot, bin);

  cout << "  " << "Result: " << bin;
  cin.get();
  return 0;
}

See working at ideone: link

    
10.02.2015 / 17:02