Need help with this program C++ (CodeBlock Program) Thank You. In C++ the larges
ID: 3573800 • Letter: N
Question
Need help with this program C++ (CodeBlock Program) Thank You.
In C++ the largest int value is 2147483647. Some real world problems require numbers larger than this. Similarly if the sum of two correct integers is larger than 2147483647, the result will be incorrect. One way to store and manipulate large integers is to store each individual digit of the number in a string and then take advantage of the fact that the characters of a string can be individually accessed by using an index value and square brackets. This exercise will involve writing a program that inputs two positive integers of at most, 20 digits and outputs the integer sum of the two input numbers. Your program will be composed of several functions: The main function, which will handle any dialog with the user (requesting input and displaying output). Main will use getNumber twice to get two multi-digit numbers and then use addNumbers to add the two numbers. The sum will be another string which will then be displayed by main. A function named getDigit to read a single numeric digit. This function should check to make sure that the input is a digit and not an alphabetic character or another nonnumeric character. Function header: char getDigit(void) A function named getNumber to read an entire multi-digit number using getDigit Function header: string getNumber(void) A function named addNumbers which will accept two strings as arguments and return a string containing the sum of the two input strings. Function header: string addNumbers(string a, string b)Explanation / Answer
char getDigit(void)
{
char ch;
cin>>noskipws>>ch;
return ch;
}
string getNumber(void)
{
string number = "";
char ch = getDigit();
while(ch != ' ')
{
number += ch;
ch = getDigit();
}
return number;
}
string addNumbers(string a, string b)
{
string out = "";
int i = a.length()-1, j = b.length()-1, carry = 0;
while(i >= 0 && j >= 0)
{
int temp = (a[i] - '0') + (b[j] - '0') + carry;
out += (temp % 10 + '0');
carry = temp / 10;
i--; j--;
}
string temp = "";
for(int i = out.length()-1; i >= 0; i--)
temp += out[i];
return temp;
}