Write two recursive functions - one should take as a parameter a C++ string of \
ID: 3758611 • Letter: W
Question
Write two recursive functions - one 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 value; the other should take as a parameter a positive int value, and return a C++ string of '1's and '0's that are the binary representation of that number (no leading zeros). The functions should be named binToDec and decToBin. Do not use any number base conversion functionality that is built into C++
I need correct answer. I posted this here before, someone gave me a completely wrong answer here
Explanation / Answer
#include <iostream>
using namespace std;
void decToBinary(int num1);
int main()
{
int num1;
cout << "Enter a non-negative integer value: ";
cin >> num1;
if (num1 < 0)
{
cout << endl << "Invalid Entry." << endl << endl;
}
else
{
cout << endl << "Decimal " << num1 << " = ";
decToBinary(num1);
cout << endl << endl;
}
return 0;
}
void decToBinary(int num1)
{
int remainder;
num1 = num1 / 2;
remainder = num1 % 2;
if (num1 > 0)
{
decToBinary(num1);
}
else if (num1 = 0)
{
cout << "0";
return;
}
cout << remainder;
}
Try this also
* C++ programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */
#include <iostream>
#include <cmath>
using namespace std;
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
int n;
char c;
cout << "Instructions: " << endl;
cout << "1. Enter alphabet 'd' to convert binary to decimal." << endl;
cout << "2. Enter alphabet 'b' to convert decimal to binary." << endl;
cin >> c;
if (c =='d' || c == 'D')
{
cout << "Enter a binary number: ";
cin >> n;
cout << n << " in binary = " << binary_decimal(n) << " in decimal";
}
if (c =='b' || c == 'B')
{
cout << "Enter a binary number: ";
cin >> n;
cout << n << " in decimal = " << decimal_binary(n) << " in binary";
}
return 0;
}
int decimal_binary(int n) /* Function to convert decimal to binary.*/
{
int rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
int binary_decimal(int n) /* Function to convert binary to decimal.*/
{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;
}
return decimal;
}
Output
Instructions:
1. Enter alphabet 'd' to convert binary to decimal.
2. Enter alphabet 'b' to convert decimal to binary.
d
Enter a binary number: 110111
110111 in binary = 55 in decimal
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.