You probably mean to initialize your arrResult[MAX] to something. Perhaps zeroes (the character '0', not the null character)?
1 2 3 4
|
for (size_t i = 0; i < MAX; i++)
{
arrResult[i] = '0';
}
|
(In your printing code, you could have it not print leading zeroes.)
Note that carries can propagate,
But the real problem is that your numbers are not aligned.
Let's say your first number is 123.
It gets filled in as { '1', '2', '3', .... }.
And then your second number is 45.
It gets filled in as { '4', '5', ... }.
Your code will then attempt to add '3' with whatever the third character of your second number is, but you want it to add '3' with 5.
So the first thing, would to make sure your numbers are aligned correctly before trying to add them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 100;
void readArr(char arr1[], size_t size)
{
for (size_t i = MAX - size; i < MAX; i++)
{
cin >> arr1[i];
}
}
void printArr(char arr1[], size_t size)
{
for (size_t i = MAX - size; i < MAX; i++)
{
cout << arr1[i];
}
cout << '\n';
}
int main() {
char arr1[MAX];
char arr2[MAX];
for (size_t i = 0; i < MAX; i++)
{
arr1[i] = '0';
arr2[i] = '0';
}
cout << "Enter the size of the first num: ";
size_t size1 = 0;
cin >> size1;
cout << "Enter the first num: ";
readArr(arr1, size1);
cout << "Enter the size of the second num: ";
size_t size2 = 0;
cin >> size2;
cout << "Enter the second num: ";
readArr(arr2, size2);
size_t largest_size = std::max(size1, size2);
printArr(arr1, largest_size);
printArr(arr2, largest_size);
return 0;
}
|
Enter the size of the first num: 3
Enter the first num: 123
Enter the size of the second num: 2
Enter the second num: 45
123
045 |
Enter the size of the first num: 5
Enter the first num: 12345
Enter the size of the second num: 7
Enter the second num: 1234567
0012345
1234567 |
With this setup, your_arr[MAX-1] will always be the least-significant digit.
your_arr[MAX-1 - 1] is then the tens place.
your_arr[MAX-1 - 2] is the hundreds place, etc.
You could have the larger number start at index 0, but you don't know what the larger number is until you've entered both, so you'd need to shift the numbers after the fact. And, if the larger number starts at index 0, then you can't do anything about 998 + 2 becoming 1000, because the 1 would drop off.