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++;
 }
}

Dani AI

Generated

Quick diagnosis for : the posted routine has the right idea but contains several bugs that cause wrong output and undefined behavior when the result should be negative. The high-level suggestions from (swap operands when the minuend is smaller) and (compare leftmost digits for equal lengths) are correct, but the implementation needs systemic fixes. Concrete problems in the posted code include returning a pointer to a local buffer (undefined behavior), using NULL as a char terminator instead of '\0'/std::string, attempting to "negate" the first byte of a returned C-string, and using negative digit values that complicate borrow logic.

A robust approach (concise):

  • Normalize inputs by trimming leading zeros.
  • Decide sign by comparing lengths, then lexicographically when lengths match.
  • Subtract larger minus smaller digit-by-digit from right to left, tracking a borrow flag.
  • Strip leading zeros from the result; return "0" if empty; prefix '-' only for non-zero results.
  • Use std::string for I/O and std::vector<int> for temporary digits; return std::string instead of char*.

Example implementation (safe and straightforward):

#include <string>
#include <vector>
#include <algorithm>

std::string subtractStrings(const std::string& a, const std::string& b) {
    auto strip = [](const std::string& s)->std::string {
        size_t p = s.find_first_not_of('0');
        return p == std::string::npos ? "0" : s.substr(p);
    };
    std::string A = strip(a), B = strip(b);
    bool negative = false;
    if (A.size() < B.size() || (A.size() == B.size() && A < B)) {
        negative = true;
        std::swap(A, B);
    }
    std::vector<int> res;
    int i = int(A.size()) - 1, j = int(B.size()) - 1, borrow = 0;
    while (i >= 0) {
        int da = A[i--] - '0';
        int db = j >= 0 ? B[j--] - '0' : 0;
        int d = da - db - borrow;
        if (d < 0) { d += 10; borrow = 1; } else borrow = 0;
        res.push_back(d);
    }
    while (res.size() > 1 && res.back() == 0) res.pop_back();
    std::string out;
    for (auto it = res.rbegin(); it != res.rend(); ++it) out.push_back(char('0' + *it));
    if (negative && out != "0") out.insert(out.begin(), '-');
    return out;
}

Quick checklist: avoid returning pointers to stack data, validate input digits, test equal operands (expect "0"), and prefer int main() with standard headers (<iostream>, <string>) instead of legacy <iostream.h>/<conio.h>.

Recommended Answers

All 2 Replies

Well one way to fix that is to see what is bigger and if the number that is being subtracted is larger than the number it is being subtracted from switch them around. Then do your normal subtraction and add a "-" to the result.

10 - 100 = -90

Swap 10 and 100 and add the negitive

100 - 10 = 90 * -1 = -90

My first suggestion is to try and subsection your code a little. Your code is complex and a bit difficult to read.
If you split it out, it will be easier to understand.

Secondly, your logic fails when a and b are of equal length when b is larger than a.
Example: a = 12345; b = 54321

To check which is larger, I suggest you check each character individually, starting with the left-most character and find which is larger. As soon as one is larger than the other, you will know which way around you have to do your subtraction.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.