Write a program to add binary numbers Use STL stack.

, by Prashant Gunjal




#include <iostream>

#include<stack>

#include<string.h>

using namespace std;

stack<int>s1;

stack<int>s2;

stack<int>s3;

int main()

 {


    char number1[5],number2[5];

    int i,a,b;



    cout<<"\nEnter the 1st binary number=";

    cin>>number1;

     for(i=0;number1[i]!='\0';i++)

      {

        if(number1[i]=='0')

         s1.push(0);

        else

         s1.push(1);

      }


    cout<<"\nEnter the 2nd binary number=";

    cin>>number2;

    for(i=0;number2[i]!='\0';i++)

     {

       if(number2[i]=='0')

s2.push(0);

         else

 s2.push(1);

     }


int carry=0,result,sum;

while(!s1.empty()||!s2.empty())

{

          a=0;

          b=0;

          if(!s1.empty())

           {

             a=s1.top();

             s1.pop();

           }

if(!s2.empty())

{

                  b=s2.top();

           s2.pop();

      }

           sum=carry+a+b;

           result=sum%2;

           s3.push(result);

           carry=sum/2;

}

     cout<<"\nAddition is = ";

      if(carry==1)

     s3.push(carry);



     while(!s3.empty())

      {

        cout<<s3.top();

        s3.pop();

      }

      cout<<"\n";

      return(0);

}


                      output:



Enter the 1st binary number=1111


Enter the 2nd binary number=1010


Addition is = 11001

0 comments: