Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++, the largest int value is 2147483647. So, an integer larger than this can

ID: 3684680 • Letter: I

Question

In C++, the largest int value is 2147483647. So, an integer larger than this cannot be stored and processed as an integer. Similarly, if the sum or product of two positive integers is greater 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 an array. Write a program that inputs two positive integers of, at most, 20 digits and outputs the sum of the numbers. If the sum of the numbers has more than 20 digits, output the sum with an appropriate message. Your program must, at least, contain a function to read and store a number into an array and another function to output the sum of the numbers.

Explanation / Answer

/* C++ code to sum large integers using string **/

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string.h>
#include <algorithm> // std::reverse
using namespace std;

void input(string &s1, string &s2) // function to take input
{
cout << "Enter 1st Integer: ";
cin >> s1; // input 1st string
cout << "Enter 2nd Integer: ";
cin >> s2; // input second string
}

string calculate_sum(string s1, string s2) // function to calculate sum
{
int i = 0;
int temp = 0;
int sum = 0;
string s = "";
while(s1[i] != '' && s2[i] != '' ) // iterating over string
{

sum = sum + temp;
sum = sum + s1[i] - '0';
sum = sum + s2[i] - '0';
if(sum > 10)
{
s = s + to_string(sum%10);
temp = sum/10; // finding carry if sun of eleemnts is greater than 10

}
else
{
s = s + to_string(sum%10);
temp = 0; // else carry will be 0
}
cout << s << endl;
i++;
sum = 0;
}
if(temp != 0)
s = s + to_string(temp);

while(s1[i] != '') // putting rest of elements in string
{
s = s + s1[i];
i++;
}

while(s2[i] != '')
{
s = s + s2[i];
i++;
}
return s;
}

int main()
{
string s1;
string s2;
  
input(s1,s2);

std::reverse(std::begin(s1), std::end(s1)); // reversing the strings
std::reverse(std::begin(s2), std::end(s2));

cout << s1<< endl;
cout << s2 << endl;
string s = calculate_sum(s1,s2);
reverse(s.begin(), s.end()); // reversing the rresult string
if(s.size() > 20)
cout << "Sum has more than 20 digits: "<< s<< endl;
else
cout << s << endl;

return 0;

}