Recently,
I had shown the program to convert from decimal to binary. It is equally
important that you know how to do the reverse process too! So let’s see how to
do it manually first. Consider the binary number ‘1010’. To convert it to
decimal, you must do the process shown:
Code:
#include<iostream> #include "math.h"; #include "conio.h"; using namespace std; int main() { int num,i,sum=0,a; cout<<"Enter the binary number : "; cin>>num; for(i=0;num!=0;i++) { a=num%10; sum=sum+a*pow(2,i); num=num/10; } cout<<"\nDecimal equivalent is : "<<sum; getch(); }
Working:
First,
the binary number is input. Inside a for loop, a variable ‘a’ is defined as
‘num%10’, i.e., the last digit of the number. Now another variable ‘sum’
(initially 0) is changed to ‘sum + (a *
pow (2, i))’. Now num is changed again into sum/10, so that on the next run of
the loop, the penultimate digit will go into the variable ‘a’. This process
continues until num reduces to 0.
Consider
the binary number 1010 as in the above figure.
1 1. On the first run, a =
num%10, i.e., a = 0. Sum changes to 0 + 0*20 = 0. ‘num’ is changed
to 101.
2 2. On the second run, a = 1.
Sum changes to 0 + 1*21 = 2. ‘num’ is now 10.
3 3. On the third, a = 0. Sum
is 2 + 0 * 22 = 2. ‘num’ is now 1.
4 4. On the forth, a = 1. Sum
is 2 + 1 * 23 = 10. ‘num’ is hence reduced to 0 and the for loop is
terminated.
Now
the variable ‘sum’ is successfully set to the decimal equivalent of the given
number i.e., 10. At last, we just output the value of ‘sum’.
Sample output for the program is given below:
Sample output for the program is given below:
Here is the program to convert Decimal Number to Binary Number:
Conversion from Decimal Number to Binary Number - C++ Program Code
Happy Coding!
:)
C++ program to convert decimal to binary
ReplyDeletethanks for this post