Rewrite and test the following function so that it returns strings representatio
ID: 3719096 • Letter: R
Question
Rewrite and test the following function so that it returns strings representations of binary numbers rather than integer representations of binary numbers.
The recursive function,
int decToBin(int d)
{
int b = 0;
if (d > 0)
{
int q = d / 2;
int r = d % 2;
b = 10 * decToBin(q) + r;
}
return b;
}
becomes the recursive function,
string decToBin(int d)
{
string b = "":
...
return b;
}
This is what was given down below.
source.cpp
#include "stdafx.h"
#include
#include
using namespace std;
int x = 0;
int y = 0;
int z = 0;
int fibN(int n)
{
x++;
if (n == 1 || n == 2)
return 1;
else
return fibN(n - 1) + fibN(n - 2);
}
int fibN(int a, int b, int n)
{
y++;
if (n == 1) return a;
else if (n == 2) return b;
else return fibN(a, b, n - 1) + fibN(a, b, n - 2);
}
int fibNN(int n)
{
int a = 0;
int b = 1;
int f = 0;
while (n > 0)
{
a = b;
b = f;
f = a + b;
n = n - 1;
z++;
}
return f;
}
int decToBin(int d)
{
int b = 0;
if (d > 0)
{
int q = d / 2;
int r = d % 2;
b = 10 * decToBin(q) + r;
}
return b;
}
string toupper(const string s)
{
string retvalue = "";
for (int i = 0; i < s.size(); i++)
retvalue = retvalue + (char)toupper(s[i]);
return retvalue;
}
int main()
{
cout << toupper("Fresno") << endl;
for(int d = 0; d <= 15; d++)
cout << decToBin(d) << endl;
cout << fibN(24) << '/' << x << endl;
cout << fibN(1, 1, 24) << '/' << y << endl;
cout << fibNN(24) << '/' << z << endl;
system("pause");
return 0;
}
Explanation / Answer
string decToBin(int d)
{
string b=""; //Intializing a string
if (d > 0)
{
int q = d / 2; //converting into binary 0 or 1
int r = d % 2;
char r1=r+'0';
b=decToBin(q)+r1; //apending the character to end of string
}
return b; //returining the string
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.