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: 3687092 • 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 he 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. (Read numbers as strings and store the digits of the number in the reverse order.)

Explanation / Answer

//This program will sum of two numbers of 20 digits

#include<iostream.h>
#include<string.h>
#include<math.h>
#include<conio.h>

int main ()
{

   string str1, str2;
   int array1[20] = {0};
   int array2[20] = {0};
   long int addition = 0;
   int temprary_addition[21] = {0};
   int limit_a = 19;
   int limit_b = 19;
   int temporary = 0;
   int power = 20;
  
   //input two numbers
   cout << "Enter for Array1";
   cin >> str1;
   cout << " "<< "Enter for Array2";
   cin >> str2;
   cout <<" ";
  
   // justification for str1 into array1
   for(int m = (str1.size())-1; m > -1; m--)
   {
       array1[limit_a] = str1[m] - '0';
       limit_a--;
   }
  
   //justification for str2 into array2
   for(int n = (str2.size())-1; n > -1; n--)
   {
       array2[limit_b] = str2[n] - '0';
       limit_b--;
   }
  
  
   for(int i=0; i<20;i++)
   {
       cout << array1[i];
   }
  
   cout <<" ";
  
   for(int j=0; j<20;j++)
   {
       cout << array2[j];
   }
  
   cout <<" ";
  


//This will present addition of individual digit
//temporary is used for having the 1 if applicable
   for(int k = 19; k > -2; k--)
   {
       if(k != -1)
       {
           if(array1[k] + array2[k] + temporary < 10)
           {
               temprary_addition[k+1] = array1[k] + array2[k] + temporary;
               temporary = 0;
           }
           else
           {
               temprary_addition[k+1] = (array1[k] + array2[k] + temporary) % 10;
               temporary = 1;
           }
       }
       else
       {
           temprary_addition[k+1] = temporary; // carries final 1 if applicable
       }
   }

   //sums up
   for(int additioncount=0; additioncount<21;additioncount++)
   {
       addition = addition + (temprary_addition[additioncount] * pow(10,power));
       power--;
   }

   cout <<" "<<addition;
  
   return 0;
}