on Leave a Comment

C++ Program to Convert Decimal to Binary Value

/*C++ Program to Convert Decimal to Binary Value*/

#include<iostream>
using namespace std;
int main()
{
    int d,rem,b=0,i=1;
    cout<<"Enter decimal number : ";
    cin>>d;
    while(d!=0)
    {
        rem=d%2;
        b=b+rem*i;
        d=d/2;
        i*=10;
    }
    cout<<endl<<"Binary : "<<b;
    return 0;
}

OUTPUT:

Enter decimal number : 8

Binary : 1000

EXPLANATION:

Assume that decimal number is 8. 
When while loop is executing 

First run
rem = 0
b = 0
d = 4
i = 10

Second run
rem = 0
b = 0
d = 2
i = 100

Third run
rem = 0
b = 0
d = 1
i = 1000

Fourth run
rem = 1
b = 1000
d = 0
i = 10000

After the fourth run while loop is terminated because the condition (d!=0) become false, value of d become 0.  

After the while loop binary value is printed.

PROGRAMS:







0 comments:

Post a Comment