I am having trouble with a program I am working on that takes in 2 numbers from the user as a string, converts the number to individual integer values stored in arrays, then displays the sum of those two numbers to the screen. My problem comes when two of the numbers that are in the same factor of 10 relative to each other add up to more than 9. I can't figure out a way to carry over the resulting one to the next factor of 10. This is what I have so far.
for (int i = 0; i < size; i++) {
val_num1[i] = val_num1[i + place_holder1];
val_num2[i] = val_num2[i + place_holder2];
if ((val_num1[i] + val_num2[i]) % 10 == val_num1[i] + val_num2[i])
val_fin[size - i - 1] = val_num1[i] + val_num2[i];
else {
val_fin[size - i] = (val_num1[i] + val_num2[i]) % 10;
val_num1[i + 1] = val_num1[i + 1] + 1;
}
}
for (int i = 0 ; i < size ; i++) {
cout << val_fin[i];
}
but I have found that this does not work. I know that one solution would involve taking the sum of the two numbers and using mod 10 to check if it is a single digit number, but I can't figure out how to get the one to carry over. Any help would be greatly appreciated. I would also be more than happy to hear about any inefficiencies or errors in conventional coding syntax for my own improvement.
val_fin is now {2, 2, 1}, or 122, the sum of 88 and 34.
This can easily be expanded to 3, 4, ... n numbers. carry will always have the correct count of "tens", making sure that the current digit doesn't exceed 10 and the following digit will have all the carry-over.
You can also do it with the modulo operator (replace the 3rd line with val_fin[i] %= 10), but the modulo operator is quite expensive and since you need the carryover anyway, I find it more logical to do it this way.