# Hugeint Class Problem

• 03-29-2008
chottachatri
Hugeint Class Problem
Hello,

As given in book of Deitel and Deitel, i am trying to make a hugeint class which adds and subtracts a 40 digit number. I have successfully done the add member function but i want help from members to make the subtract function successful. I have done it and it works for some data sets but for some it doesn't. This is the code that i have worked so far

Code:

``` #include <iostream.h> #include <string.h> class hugeint {   int a[40];   char s[40];         public:                 hugeint(){}                 hugeint(char *);                 void operator+(hugeint);                 void operator-(hugeint);                 void putdata(); }; void hugeint::operator+(hugeint b) {  int i,l,carry=0;  hugeint temp;  if(strlen(s)>strlen(b.s))         l=strlen(s);  else         l=strlen(b.s);  for(i=39;i>=40-l;i--)  {   temp.a[i]=a[i]+b.a[i]+carry;   carry=0;   if(temp.a[i]>9)   {                 carry++;                 a[i]=a[i]%10;   }  }  if(a[i]>9)  {         a[i]=a[i]%10;         a[i-1]=1;         l++;  }  cout<<"\n\nThe Addition Is :\n";  for(i=40-l;i<40;i++)         cout<<temp.a[i]; } void hugeint::operator-(hugeint b) {   int i,l,borrow;   hugeint temp;  if(strlen(s)>strlen(b.s))         l=strlen(s);  else         l=strlen(b.s);  for(i=39;i>=l;i--)  {         temp.a[i]=a[i]-borrow-b.a[i];         borrow=0;         if(temp.a[i]<0)         {                 borrow++;                 temp.a[i]=a[i]+10-b.a[i];         }  }  cout<<"\n\nThe Subtraction Is :\n";   for(i=40-l;i<40;i++)         cout<<temp.a[i]; } void hugeint::putdata() {  int i;  cout<<"\n\nThe Number Is :\n";  for(i=40-strlen(s);i<40;i++)         cout<<a[i]; } hugeint::hugeint(char *t) {         strcpy(s,t);         for(int i=0;i<40;i++)                 a[i]=0;         int j;         for(i=40-strlen(s),j=0;i<40;j++,i++)                 a[i]=s[j]-'0'; } int main(void) {  hugeint a("871"),b("77");  a.putdata();  b.putdata();  a-b;  return 0; }```
• 03-29-2008
iMalc
I'd say the problem is here:
Code:

`                temp.a[i]=a[i]+10-b.a[i];`
That doesn't take 'borrow' into account. I think you should replace that line with just:
Code:

`                temp.a[i] += 10;`
• 03-29-2008
chottachatri
Thanks Imalc works like a charm now!