Sunday 23 October 2016

Addition of Binary numbers using Standard Template Library

/*
TITLE:
Write C++ program using STL to add binary numbers ; use STL stack.
*/
#include<iostream>
#include<stack>
using namespace std;
stack<int> read()
{
stack<int> s;
int x,n,i;
n=4;
cout<<"\nEnter 4 bit binary number : ";
for(i=0;i<n;i++)
{
cin>>x;
s.push(x);
}
return s;
}

void display(stack<int> &s)
{
cout<<" ";
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}

stack<int> add(stack<int> &s1,stack<int> &s2)
{
stack<int> s;
int sum,carry=0,b1,b2;
while(!s1.empty()||!s2.empty())
{
b1=b2=0;
if(!s1.empty())
{
b1=s1.top();
s1.pop();
}
if(!s2.empty())
{
b2=s2.top();
s2.pop();
}
sum=(b1+b2+carry)%2;
carry=(b1+b2+carry)/2;
s.push(sum);
}
if(carry==1)
s.push(1);
return s;
}

int main()
{
stack<int> s1,s2,s3;
int c;
char ch;
do
{
cout<<"Binary Addition\n";
cout<<"1.accept a numbers(give space after each bit)\n";
cout<<"2.Display addtion of two numbers\n";
cout<<"Enter your choice..:\n";
cin>>c;
switch(c)
{
case 1:
s1=read();
s2=read();
break;
case 2:
cout<<"\nThe result of addition is : ";
s3=add(s1,s2);
display(s3);
break;
}
cout<<"\ndo you want to continue?\n";
cin>>ch;
}while(ch=='y'||ch=='Y');
return 0;
}

No comments:

Post a Comment