Hi! I have written a code to subtract 2 large integers stored in arrays! But the problem is, its not working when the minuend is smaller than the subtrahend, i.e, when the answer would be negative. I am taking 2 char arrays as parameters, converting them to int arrays, working with them, storing the result in a char array & returning it! Can somebody please point out the optimizations needed in the code!
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Sub{
public:
char *subArray(char a[], char b[])
{
int i, j, k, diff[255], borr, size1=0, size2=0, x[255], y[255];
char temp[255], *p;
cout<<"\nNuM1: " ;
for(i=0; a[i]!=NULL; i++)
{
x[i]=a[i]-'0'; //conversion into int array
size1++;
cout<<x[i];
}
cout<<"\nNuM2: " ;
for(i=0; b[i]!=NULL; i++)
{
y[i]=b[i]-'0'; //conversion into int array
size2++;
cout<<y[i];
}
if(size1<size2)
{
p=subArray(b, a);
p[0]=-p[0]; //not printing the correct value
return p;
}
else
{
for(j=0; j<size2; j++)
{
y[j]=-y[j];
}
k=borr=0;
for(i=size1-1, j=size2-1;i>=0 && j>=0; i--, j--, k++)
{
diff[k]=x[i]+y[j]-borr;
if(diff[k]<0)
{
diff[k]+=10;
borr=1;
}
else
borr=0;
}
if(i>=0)
{
for(;i>=0;i--,k++)
{
diff[k]=x[i]-borr;
if(diff[k]<0)
{
diff[k]+=10;
borr=1;
}
else
borr=0;
}
}
i=j=0;
for(i=k-1; i>=0; i--)
{
if(diff[i]<0)
{
temp[j++]='-';
temp[j++]=-(diff[i])+'0';
}
else
temp[j++]=diff[i]+'0';
}
temp[j]='\0';
return temp;
}
}
};
void main()
{
Sub s;
char num1[255], num2[255], *diff;
cout<<"NuM1: ";
cin>>num1 ;
cout<<"\nNuM2: ";
cin>>num2;
diff = s.subArray(num1, num2);
cout<<"\nDifference: ";
while(*diff != NULL)
{
cout<<*diff;
diff++;
}
}