Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Don\'t try to use any loops when writing a recursive function. If you do, there\

ID: 3759947 • Letter: D

Question

Don't try to use any loops when writing a recursive function. If you do, there's a very good chance your function won't be truly recursive.

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++.

The file must be named: recursive.cpp

Explanation / Answer

conversion of binary to decimal and decimal to binary using recursive with out using loops

RECURSIVE.CPP

#include<iostream>//header file

#include <math.h>//header file
using namespace std;
int sum=0;
int binaryToDecimal( int, int );//function declaraion

long toBinary(int);//function declaraion

int main(){

long binaryNo;
int decimalNo;
int bitWeight;
int binaryNum;
bitWeight = 0;

cout<<"Enter any decimal number: ";//keyboard inputting
cin>>decimalNo;

binaryNo = toBinary(decimalNo);
cout<<"binary no of "<<decimalNo<<"is "<<binaryNo;

cout <<"enter a number in binary: ";
cin >> binaryNum;
cout << endl;
int sum = binaryToDecimal(binaryNum, bitWeight);
cout << "Binary " << binaryNum << "= "<< sum<< endl;

return 0;
}

long toBinary(int decimalNo){//function to convr binary

static long binaryNo,remainder,factor = 1;

if(decimalNo != 0){

remainder = decimalNo % 2;
binaryNo = binaryNo + remainder * factor;
factor = factor * 10;
toBinary(decimalNo / 2);
}

return binaryNo;
}
int binaryToDecimal( int binaryNumber, int weight )
{//function to convert decimal
  
int bit;
if ( binaryNumber > 0 ){
bit = binaryNumber % 10;
sum = sum + bit * pow(2, weight );
binaryNumber = binaryNumber / 10;
weight++;
binaryToDecimal(binaryNumber, weight );
}
return sum;
}

output

Enter any decimal number: 11 binary no of 11is 1011

enter a number in binary: 111 Binary 111= 7

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote