91.9k views
2 votes
Write a function decimalToBinaryRecursive that converts a decimal value to binary using recursion. This function takes a single parameter, a non-negative integer, and returns a string corresponding to the binary representation of the given value. The function name: decimalToBinaryRecursive The function parameter: An integer to be converted to binary Your function should return the binary representation of the given value as a string Your function should not print anything Your function should use recursion. Loops are not allowed.

User Sylke
by
4.5k points

1 Answer

4 votes

Answer:

Check the explanation

Step-by-step explanation:

#include <iostream>

#include <string>

using namespace std;

string decimalToBinaryRecursive(int n) {

if(n == 0) {

return "0";

} else if(n == 1) {

return "1";

} else {

int d = n % 2;

string s;

if (d == 0) {

s = "0";

} else {

s = "1";

}

return decimalToBinaryRecursive(n/2) + s;

}

}

int main() {

cout << decimalToBinaryRecursive(0) << endl;

cout << decimalToBinaryRecursive(1) << endl;

cout << decimalToBinaryRecursive(8) << endl;

return 0;

}

See the output image below

Write a function decimalToBinaryRecursive that converts a decimal value to binary-example-1
User DBug
by
4.8k points