I am trying to add two numerical char arrays such as:

"124" and "589"

I wrote functions to reverse the string and add the strings, and it works for strings like "123" and "456", but when the last digits are greater than 10, I don't know how to carry it, since the string is in reverse. Here's my code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char* addNum(char* n1, char* n2, int max_size);

void reverseStr(char* str);
bool isEven(int i);
void flipChar(char &ch1, char &ch2);

int main() 
{
    char *n1, *n2, ch, *res;
    int max_size;
    
    cout << "Maximum number of digits: ";
    cin >> max_size;

    max_size += 2;
    
    n1 = new char[max_size];
    n2 = new char[max_size];
    
    while ((ch = cin.get()) != '\n' && ch != -1);
    
    cout << "Enter first number: ";
    cin.getline(n1, max_size);
    
    while ((ch = cin.get()) != '\n' && ch != -1);
    
    cout << "Enter second number: ";
    cin.getline(n2, max_size);
    
    res = addNum(n1, n2, max_size);
    
    cout << "Result: ";

    cout << res;
    
    return 0;
}
 
char* addNum(char* n1, char* n2, int max_size)
{
    int max, greater_len, n, carry, i;
    char *res;
    
    carry = 0;
    res = new char[max_size + 3];
    
    if (strlen(n1) > strlen(n2))
    {
        max = strlen(n2); 
        greater_len = strlen(n1) - strlen(n2);
    }
    else if (strlen(n1) < strlen(n2))
    {
        max = strlen(n1);
        greater_len = strlen(n2) - strlen(n1);
    }
    else
    {
        max = strlen(n1);
        greater_len = 0;
    }

    
    reverseStr(n1);
    reverseStr(n2);
    
    for (i = 0; i < max; i++)
    {
        n = (n1[i] - '0') + (n2[i] - '0') + carry;
        carry = 0;
        while (n >= 10)
        {
            n -= 10;
            carry++;
        }
        res[i] = n + '0';
        if ((i == max - 1) && (carry > 0))
        {
            i++;
            res[i] = carry;
        }
    }
    
    if (greater_len != 0)
    {
        for (i = max; i < max + greater_len; i++)
        {
            n = (n1[i] - '0') + (n2[i] - '0') + carry;
            carry = 0;
            while (n >= 10)
            {
                n -= 10;
                carry++;
            }
            res[i] = n;
        }
    }
    
    res[i] = '\0';
    reverseStr(res);
    return res;
}

void reverseStr(char* str)
{
    char *front, *rear, ch;
    front = str;
    rear = str + strlen(str) - 1;
    
    if (isEven(strlen(str)))
    {
        while (front != str + ((strlen(str) / 2) - 1))
        {
            flipChar(*front, *rear);
            front++;
            rear--;
        } 
    }
    else
    {
        while (front != rear)
        {
            flipChar(*front, *rear);
            front++;
            rear--;
        }
    }
}

bool isEven(int i)
{
    if (i % 2 == 0)
        return true; //EVEN
    return false; //ODD
}

void flipChar(char &ch1, char &ch2)
{
    char ch;
    ch = ch1;
    ch1 = ch2;
    ch2 = ch;
}

Thanks

I'm guessing the point of this program is not to use an integer to store the values and then add them to get the result. Right? Because in that case, the program would just be:

#include <iostream>
using namespace std;

int main() {
  int a,b;
  cout << "\nEnter first number: "; cin >> a; cin.ignore();
  cout << "\nEnter second number: "; cin >> b; cin.ignore();
  cout << "\nThe result comes to: " << (a + b) << endl;
  return 0;
};

Now, are you required to use char arrays? If you are, I find it a bit sadistic on the teacher's part. In C++, we use std::string for things like that because it's so much better.

If you are forced to use char arrays, there are a few things to know. First, don't abuse the strlen() function. This function loops through the characters until it finds a null-character. It's just a waste to compute this more than once for a string. Compute it and store it in a local variable, don't recompute it over and over like you do on lines 52 to 66 for example.

Second, don't make functions that allocate a char array and then output a pointer to it. That's just a recipe for disaster. Preallocate the "output" string and pass the pointer as a parameter (like all str functions do (strlen, strcpy, strcmp, substr, etc.)).

Third, anything you allocate needs to be deallocated (i.e. every new-statement has to be matched with a delete-statement). In your simple code, that doesn't really matter, but it is a habit to develop at the earliest stage possible.


On the actual algorithm, you have some serious problems. Your loops at lines 72 and 91 assume that both input strings are the same length, which is not a good thing. You shouldn't do it this way. I propose two options. One is to fill the shortest string with leading zero characters (not null, but zero: '0') and do the algorithm for two strings of the same length.

Second option is to do a loop somewhat like this:

//after having reversed the strings.
  int n1_len = strlen(n1); //precompute lengths.
  int n2_len = strlen(n2); //idem.
  int max = (n1_len > n2_len ? n1_len : n2_len); //get max
  for(int i=0;i<max;++i) {   //loop until max
    if(i >= n1_len) {
      //add only n2 digits.
    } else if(i >= n2_len) {
      //add only n1 digits.
    } else {      //at this point, i has to be less than both n1_len and n2_len:
      //add both n1 and n2 digits together.
    };
  };

Additional note: you don't need to reverse the strings. All you need to do is to take the index "n1_len - i - 1" instead of "i" in the reversed string.

Finally, lines 76 to 80 and 95 to 99, take a look at that loop for a second. How is this loop not just the exact same as this (I also corrected the res thing):

carry += n / 10;
  res[i] = (n % 10) + '0';

If you implement what I suggest, I think the length of your program will be cut by 75% easily.

Thanks!

n1_len > n2_len ? n1_len : n2_len

Can you explain this part please?

EDIT: Never mind, found out.

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.