Write a program for the following: Assume that your computer has the very limite
ID: 3552660 • Letter: W
Question
Write a program for the following:
Assume that your computer has the very limited capability of being able to read and write
only single-integer digits and to add two integers consisting of one decimal digit each. Write a
program that can read two integers up to 30 digits each, add these integers together, and
display the result. Test your program using pairs of numbers of varying lengths.
Hint: Store the two numbers in two int arrays of size 30, one digit per array element. If the
number is less than 30 digits in length, enter enough leading zeros (to the left of the number)
to make the number 30 digits long.
You will need a loop to add the digits in corresponding array elements. Don
Explanation / Answer
#include<iostream>
#include<string>
#include<fstream>
#include<conio.h>
using namespace std;
void AddTwoArray(int [],int [],int []);
int main()
{
char FirstNumberString[30], SecondNumberString[30];
int FirNum[30], SecNum[30];
int Sum[31];
ifstream myReadFile;
myReadFile.open("input.txt");
cout << "Enter two numbers :" << endl;
myReadFile >> FirstNumberString >> SecondNumberString;
myReadFile.close();
//convert string to int
int i;
//First Number
for (i=0; i<30-strlen(FirstNumberString); i++)
FirNum[i]=0;
for (int j=0; i<30; i++, j++)
{
FirNum[i]=FirstNumberString[j]-48;
}
//for second number
for(i=0;i<30-strlen(SecondNumberString);i++)
SecNum[i]=0;
for(int j=0;i<30;i++,j++)
{
SecNum[i]=SecondNumberString[j]-48;
}
AddTwoArray(FirNum, SecNum, Sum);
//addition print
ofstream output;
output.open("input.txt");
cout << " Addition of both numbers is :";
for (int i=0; i<31; i++)
{
if (Sum[i]==0)
continue;
output << Sum[i];
}
output.close();
getch();
}
void AddTwoArray(int F[], int S[], int sum[])
{
int carry =0;
for (int i=29; i>=0; i--)
{
if (S[i]+F[i]+carry>9)
{
sum[i+1]=(S[i]+F[i])%10;
carry=1;
}
else
{
sum[i+1]=(S[i]+F[i]);
carry=0;
}
}
sum[0]=carry;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.