porithm recursion to convert a number in binary (from 1 to 10) to umC+program us
ID: 3870153 • Letter: P
Question
porithm recursion to convert a number in binary (from 1 to 10) to umC+program using utput the st states that each successive digit in the number is mul- cimal number. The al number. The algorithm states th the power corresponding to its position in the number. de by the base (2) raised to se (2) raised to correspon ipleorder digit is in position 0. We sum together all of these products to get the 001, we convert it to The lo value. For example, if we have the binary number 111 decimal decimal as follows: 1.20 1 0-2 =0 *22 = 0 1 23 -8 1-216 125 32 Decimal value = 1 + 0 + 0 + 8 + 16 + 32-57 A recursive formulation of this algorithm can extract each digit and compute the c responding power of the base by which to multiply. Once the base case (the last digi extracted), the function can sum the products as it returns. In C++ we can represent a binary number using integers. However, there is a ger-the user can enter an invalid number by typing a digit that's unrepresentab the base. For example, the number 1011201 is an invalid binary number because 2 allowed in the binary number system. Your program should check for invalid di they are extracted, handle the error in an appropriate way (that is, it shouldn't a numerical result), and provide an informative error message to the user.Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
label:
long int binnum, decnum=0, i=1, rem;
cout<<endl<<"Enter binary number : ";
cin>>binnum;
while(binnum!=0)
{
rem=binnum%10;
if(rem>1){
cout<<"Error not a binary number ."<<endl;
cout<<"Enter Binary Number Which has only 1's and 0's : ";
goto label;
}else{
decnum=decnum+rem*i;
i=i*2;
binnum=binnum/10;
}
}
cout<<"Equivalent decimal value = "<<decnum;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.