Sunday, 18 January 2015

C++ program for adding two binary numbers



C++ program for adding two binary numbers
#include<iostream>
using namespace std;
int main()

{

    long bin1, dec1 = 0, rem1, num1, base1 = 1;

    cout << "Enter the binary number(1s and 0s) : ";
    cin >> num1;

    bin1 = num1;

    while (num1 > 0)                                                 //loop for converting first binary no to
    {                                                                          //decimal no
                 rem1 = num1 % 10;
        dec1 = dec1 + rem1 * base1;
        base1 = base1 * 2;
        num1 = num1 / 10;

    }
               
    long bin2, dec2 = 0, rem2, num2, base2 = 1, sum_dec=0;

    cout << "Enter the Second binary number(1s and 0s) : ";
    cin >> num2;

    bin2 = num2;

    while (num2 > 0)                                                 //loop for converting second binary no to
    {                                                                          //decimal no
        rem2 = num2 % 10;
        dec2 = dec2 + rem2 * base2;
        base2 = base2 * 2;
        num2 = num2 / 10;

    }

                sum_dec=dec1+dec2;                             //adding first and second decimal number
               
                int a=1,sum=0;

                while(sum_dec!=0)                                //converting decimal to binary
                {
                                sum+=(sum_dec%2)*a;
                                sum_dec=sum_dec/2;
                                a=a*10;
                                if(sum_dec==0)
                                                break;
                }
                                cout<<"Sum of Binary Numbers is : "<<sum<<endl;
               
                return 0;
}
Output of the program:
Sample # 1:
Sample # 2:

No comments:

Post a Comment