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=0When user enters a decimal number say 105, then it gets stored in decimalNum. So decimalNum=105Now the condition decimalNum!=0 (of while loop) gets evaluatedThe condition decimalNum!=0 or 105!=0 evalutes to be true, therefore program flow goes inside the loopAnd decimalNum%2 or 105%2 or 1 gets intialized to binaryNum[i] or binaryNum[0]. So, binaryNum[0]=1The value of i gets incremented. Now i=1And decimalNum/2 or 52 gets initialized to decimalNum. Now decimalNum=52Program 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 loopAnd again, decimalNum%2 or 52%2 or 0 gets initialized to binaryNum[i] or binaryNum[1]. So binaryNum[1]=0Again the value of i gets incremented. So i=2And then decimalNum/2 or 52/2 or 26 gets initialized to decimalNum. So decimalNum=26Process the same, from step no.8 to 12 with new value of decimalNum and iOn 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]=1binaryNum[1]=0binaryNum[2]=0binaryNum[3]=1binaryNum[4]=0binaryNum[5]=1binaryNum[6]=1When 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 printedThe value of binaryNum[] gets printed from its last to 0th indexThat 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