I am a beginner and I am stuck on this problem. Please any help will do. Thank y
ID: 3539475 • Letter: I
Question
I am a beginner and I am stuck on this problem. Please any help will do. Thank you in advance
In c++, the largest int value is 2147483647. So, an integer larger than this cannot be stored and processed as an integer. Similarily, 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 integes 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 stor a number into an array and another function to output the sum of the numbers. (Hint: read numbers as stings and stor the digits of the number in the reverse order.)
Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
int addnum(int[], int[],int, int);
int readnum(int[]);
void display(int[], int);
int main()
{
int num1;
int num2;
int sum1;
int numone[20]={0};
int numtwo[20]={0};
int sum2[20]={0};
cout<<"This is a program that inputs two positive integers of, at most, 20 digits and then outputs the sum of the numbers.";
cout<<endl;
cout<<"Please enter the first positive integer (20 digits at the most): ";
cin>>num1;
cout<<endl;
cout<<endl;
num1=readnum(numone);
cout<<"Enter the second postitive integer (20 digits at the most): ";
cin>>num2;
cout<<endl;
cout<<endl;
num2=readnum(numtwo);
cout<<endl<<endl;
cout<<"First large integer is "<<(numone, num1)<<" ";
cout<<endl;
cout<<"The second large integer is "<<(numtwo,num2)<<" ";
cout<<endl;
sum1=addnum(numone, numtwo,num1, num2);
if(sum1<=20)
{
cout<<"Sum of the two large integers: "<<(sum1, sum2);
}
else
{
cout<<"The outcome of the sum of the two large numbers has 21 digits. The sum of the two large integers: "<<(sum1, sum2);
}
cout<<endl;
cout<<endl;
cout<<endl;
return 0;
}
int readnum(int num[20])
{
string number;
getline(cin, number);
for(int i=2; i<(int)number.length(); i++)
num[i]=(int) number[number.length()-1-i]-48;
return number.length();
}
int addnum(int a[20], int b[20], int sum[20], int ab,int bc)
{
int carry=0;
int len;
int temp;
int i;
if(ab>bc)
len=ab;
else
len=bc;
for(i=0; i<len; i++)
{
temp=a[i]+b[i]+carry;
sum[i]=temp%10;
carry=temp/10;
}
if(carry==0)
return len;
else
sum[i]=carry;
return len+1;
}
void display(int a[20], int n)
{
for(int i=n-1; i>-1;i--)
cout<<a[i];
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.