Binary Subtraction Code
Here I have done my coding
Coding concept used :
- ARRAYS
- POINTERS
- You should have to use binary numbers of same bits i.e: same size.
- First you have to enter two Binary numbers.
- This program then calculate the complement of 2nd number.
- It will then add two binary numbers according to addition rule.
- It will display then result.
- If in result the extreme left digit is carry(1) then this program will add this carry in original result.
- If their is no carry(0) then this program will take again the complement of original result.
#include <iostream>
#include<string>
using namespace std;
int main()
{
int size,size2;
cout<<"\t\tEnter two Binary numbers you want to Subtract\n";
cout<<"\nEnter the first number size : ";
cin>>size2;
int *num1=new int[size2];
cout<<"Enter the first number of declared size : \n";
for(int i=0;i<size2;i++)
{
cin>>num1[i];
}
cout<<"\nEnter the second number size : ";
cin>>size;
int carry=0;
int *result=new int[size+1];
int *num2 = new int[size];
cout<<"Enter the Second number of declared size : \n";
for(int c=0;c<size;c++)
{
cin>>num2[c];
if(num2[c]==1)
{
num2[c]=0;
}
else
{
num2[c]=1;
}
}
cout<<"\nThe inverse of second number is : ";
for(int c=0;c<size;c++)
{
cout<<num2[c];
}
cout<<"\n\nResult of two numbers is : ";
for(int a=size-1;a>=0;a--)
{
if(num1[a]+num2[a]+carry==3)
{
result[a]=1;
carry=1;
}
else if(num1[a]+num2[a]+carry==2)
{
result[a]=0;
carry=1;
}
else if(num1[a]+num2[a]+carry==1)
{
result[a]=1;
carry=0;
}
else if(num1[a]+num2[a]+carry==0)
{
result[a]=0;
carry=0;
}
}
result[size]=carry;
for(int t=0;t<size;t++)
{
cout<<result[t];
}
if(result[size]==1)
{
cout<<"\n\nAs their is carry 1 so\n";
cout<<"The number after adding carry is : ";
int carry1=0;
int *fresult=new int[size2];
for(int p=0;p<size;p++)
{
fresult[p]=result[p];
}
for(int z=size-1;z>=0;z--)
{
if(fresult[z]+1+carry1==1)
{
fresult[z]=1;
carry1=0;
break;
}
else if(fresult[z]+1+carry1==2)
{
fresult[z]=0;
carry1=1;
if(carry1==1)
{
for(int d=size-2;d>=0;d--)
{
if(fresult[d]+carry1==1)
{
fresult[d]=1;
carry1=0;
}
else if(fresult[d]+carry1==2)
{
fresult[d]=0;
carry1=1;
}
}
break;
}
}
}
for(int c=0;c<size2;c++)
{
cout<<fresult[c];
}
delete[] fresult;
}
else
{
cout<<"\n\nAs Their will be No carry so\n";
cout<<"Final Number after inverse is : ";
for(int x=0;x<size2;x++)
{
if(result[x]==1)
{
result[x]=0;
}
else
{
result[x]=1;
}
cout<<result[x];
}
}
cout<<endl;
delete[] result;
delete[] num2;
delete[] num1;
}
No comments:
Post a Comment