ImportantC++program for binary number to decimal number

 C++program for binary number to decimal number

#include<iostream>
using namespace std;
int main()
{
    int binnum, decnum=0, i=1, rem;
    cout<<"Enter any Binary Number: ";
    cin>>binnum;
    while(binnum!=0)
    {
        rem = binnum%10;
        decnum = decnum + (rem*i);
        i = i*2;
        binnum = binnum/10;
    }
    cout<<"\n Decimal Value = "<<decnum;
   
    return 0;
}

**************Important**"****************

Initially decnum=0, i=1 and binnum=1111010 (entered by user)
The condition binnum!=0 (inside the while loop) or 1111010!=0 evaluates to be true
Therefore program flow goes inside the loop
And binnum%10 or 1111010%10 or 0 gets initialized to rem. Now rem=0
Similarly, decnum+(rem*i) or 0+(0*1) or 0 gets initialied to decnum. Now decnum=0
Then i*2 or 1*2 or 2 gets initialized to i. Now i=2
And at last, binnum/10 or 1111010/10 or 111101 gets initialized to binnum. Now binnum=111101
After executing all the four statements of while loop (for first time), we have decnum=0, i=2 and binnum=111101
Program flow goes back to the condition of while loop
Again the condition binnum!=0 or 111101!=0 evalutes to be true, therefore program flow again goes inside the loop
And binnum%10 or 111101%10 or 1 gets initialized to rem. Now rem=1
Similarly, decnum+(rem*i) or 0+(1*2) or 2 gets initialized to decnum. Now decnum=2
And i*2 or 2*2 or 4 gets initialized to i. Now i=4
And at last, binnum/10 or 111101/10 or 11110 gets initialized to binnum. Now binnum=11110
Now process from step no.9 to 14 with new value of decnum, i and binnum
Now we have decnum=2, i=8 and binnum=1111
Go to step no.15
Now we have decnum=10, i=16, and binnum=111
Go to step no.15
Now we have decnum=26, i=32, and binnum=11
Go to step no.15
Now we have decnum=58, i=64, and binnum=1
Go to step no.15
Now we have decnum=122, i=128, binnum=0

Comments

Popular Posts