Convert natural number to binary recursively

Asked

Viewed 8,270 times

5

How can I turn this function into a recursive function? I managed to make it iterative in 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;
}

3 answers

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 it working on ideone: http://ideone.com/UvF4K2

4


If the intention is just to do 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);
}

See on ideone. Adapted from this reply.

  • I know this is a question outside the scope, but because you declared the function above the main() and just wrote it below ? has increased performance or readability of code ? or and just matter of taste ?

  • It’s been a long time since I programmed in c++. The code gave error when compiling. I chose to declare the function instead of passing it over main, for no particular reason, was what occurred to me at the time.

0

void questao3(int i) {
  if (i > 1) {
    questao3(i / 2);
    if (i) printf("%d", i % 2);
  }
  if ((i == 1) || (!i))
    printf("%d", i);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.