Write a recursive function that should take as a parameter a C++ string of \'1\'
ID: 3759694 • Letter: W
Question
Write a recursive function that should take as a parameter a C++ string of '1's and '0's that are the binary representation of a positive integer, and return the equivalent int data type decimal value. Do not use any number base conversion functionality that is built into C++.
I need a correct answer. I posted this here three times before, people gave me completely wrong or irrelevant answers.
important notes:
-Function must have string parameter and return integer (so NO void is allowed)
-you are not allowed to use any loops when writing a recursive function.
-you are not allowed use stringstream.
Explanation / Answer
#include <iostream>
void decToBin(int num1);
void binToDec(string bin, int i);
int main()
{
int num1;
string bin;
cout << "Enter a non-negative integer value: ";
cin >> num1;
if (num1 < 0)
{
cout << endl << "Invalid Entry." << endl << endl;
}
else
{
cout << endl << "Decimal " << num1 << " = ";
decToBin(num1);
}
cout << "Enter Binary number : ";
cin >>bin;
binToDec(bin, 0);
return 0;
}
void decToBin(int num1)
{
int remainder;
num1 = num1 / 2;
remainder = num1 % 2;
if (num1 > 0)
{
decToBin(num1);
}
else if (num1 = 0)
{
cout << "0";
return;
}
cout << remainder;
}
void binToDec(string binary, int i)
{
double decNum=0;
if (i >= 0)
{
if (binary[i] == 1)
{
decNum = (decNum + pow(2, i));
}
else if (binary[i] == 0)
{
decNum = (decNum + 0);
}
bin2dec(binary, i - 1);
cout << decNum;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.