ImportantC++ code for decimal to binary number
/*C++ code for decimal to binary number*/
#include<iostream>
using namespace std;
int main()
{
int decimalNum, binaryNum[20], i=0;
cout<<"Enter the Decimal Number: ";
cin>>decimalNum;
while(decimalNum!=0)
{
binaryNum[i] = decimalNum%2;
i++;
decimalNum = decimalNum/2;
}
cout<<"\nBinary Value: ";
for(i=(i-1); i>=0; i--)
cout<<binaryNum[i];
cout<<endl;
return 0;
}
****************Important***********
Initial value, i=0
When user enters a decimal
number say 105, then it
gets stored in decimalNum.
So decimalNum=105
Now the condition decimalNum!=0
(of while loop) gets evaluated
The condition decimalNum!=0
or
105!=0 evalutes to be true,
therefore program flow goes
inside the loop
And decimalNum%2 or 105%2
or
1 gets intialized to binaryNum[i]
or
binaryNum[0]. So, binaryNum[0]=1
The value of i gets incremented.
Now i=1
And decimalNum/2 or 52 gets
initialized to decimalNum.
Now decimalNum=52
Program flow goes back and
evaluates the condition of
while loop again with new
value of decimalNum (52)
Because again the
condition evaluates to be true,
therefore program flow
again goes inside the loop
And again, decimalNum%2
or
52%2 or 0 gets initialized
to binaryNum[i]
or
binaryNum[1]. So binaryNum[1]=0
Again the value of i gets
incremented.
So i=2
And then decimalNum/2 or
52/2 or 26 gets initialized to
decimalNum. So decimalNum=26
Process the same, from step no.8
to 12 with new value of
decimalNum and i
On continuing the process
in similar way until
the condition of while
loop evaluates to be false,
we will get the values of
binaryNum[] as:
binaryNum[0]=1
binaryNum[1]=0
binaryNum[2]=0
binaryNum[3]=1
binaryNum[4]=0
binaryNum[5]=1
binaryNum[6]=1
When the value of decimalNum
becomes equal to 0,
then the condition decimalNum!=0
or
0!=0 evaluates to be false,
therefore the evaluation of
while loop gets ended.
And using for loop,
the value of binaryNum[]
gets printed
The value of binaryNum[]
gets printed from its last
to 0th index
That will be, 1101001
*********************************
#include<iostream>
using namespace std;
int main()
{
int decnum, binnum=0, i=1, rem;
cout<<"Enter any decimal Number: ";
cin>>decnum;
while(decnum!=0)
{
rem = decnum%2;
binnum = binnum + (rem*i);
i = i*10;
decnum = decnum/2;
}
cout<<"\n binary Value = "<<binnum;
return 0;
}
Comments
Post a Comment