Answers
Question 1
#include<iostream>
using namespace std;
int main()
{
char c;
cin>>c;
int r, m, sum = 0, b = 1;
if(c=='0'||c=='1')
{m=c-48;
while (m > 0)
{
r = m % 10;
sum = sum + r * b;
b *= 2;
m /= 10;
}
cout<<sum;}
else
cout<<"The character "<<c<<" is invalid: "<<c<<" is not a bit.";
}
explaination----
First of all a character is taken as input in c . then some initialization is done which i'll be coming through in between . if condition is executed so to check if the entered character is bit or not and if yes then the conversion of it into its decimal equivalent will be done .
now since we stored an integer value in a character variable , so it's ascii value will be stored in it not the original one. So to take the original value for conversion we subtracted 48 from it to get the digit.
And then stored in a variable named m.
Now the .conversion starts . a loop is executed till m>0. we are taking modulus of m on dividing it by 10 so to take its digits at 10th place . and on everytime dividing m by 10 we will have the next digit at 10th place so we will be able to get all the digits with us. now what are we doing with those digits .?
As we know for conversion from binary to decimal we multiply the digits of binary with 2 raised to the power (0,1,2,3,4,.....)
with the power for the LSB being 0(2 raised to the power 0) then increasing the power by 1 subsequently from right to left.
Here r stored the digits , b is having the powers of 2 which is increased in the 3rd line of the loop .
And in the second line we are having all the calculations stored in the sum variable which at last will be having the final value conversion into decimal. The fourth line is dividing m by 10 so each of its digit will come at 10th place eventually.
Then we printed the value converted.
This all comes in the if case , and by the way if user has input other character than 0 or 1 it will print the message invalid. which is shown in the above image.
#as per HomeworkLib guidelines i am supposed to answer only first question so plz post them separately.