1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
using namespace std;
const int MAXIMUM_DIGITS = 20;
void input_Large_Int (int a[], int& size_of_A); //input function for the two big integers
void output_Large_Int(int a[], int size_of_A); //output function for the two big integers and the sum integer
void add(int a[], int size_of_A, int b[], int size_of_B, int sum[], int & size_Sum); //add function for the big integers' sum
int main()
{
//Declare arrays
int a[MAXIMUM_DIGITS], b[MAXIMUM_DIGITS], sum[MAXIMUM_DIGITS];
//Declare arrays' size
int size_of_A, size_of_B, size_Sum;
//declare char type for program answer response
char answer;
for(int i = 0; i < MAXIMUM_DIGITS - 1; i++)
{
a[i] = 0;
b[i] = 0;
sum[i] = 0;
}
//perform do-while loop until user answers with "n" or "N"
do {
//accept first user integer input
input_Large_Int(a, size_of_A);
//accept second user integer input
input_Large_Int(b, size_of_B);
//add arrays
add(a, size_of_A, b, size_of_B, sum, size_Sum);
//display the integers that were added and their sum
cout << "The sum of \n";
output_Large_Int(a, size_of_A);
cout << " and ";
output_Large_Int(b, size_of_B);
cout << " is ";
output_Large_Int(sum, size_Sum);
cout << "\n\n";
//ask if user wishes to continue
cout << "Add two more? (y or n): ";
cin >> answer;
}
while (answer == 'y' || answer == 'Y');
system("pause");
return EXIT_SUCCESS;
}
//define input for the big integer function
void input_Large_Int(int a[], int& size_of_A)
{
char digit[MAXIMUM_DIGITS];
char change;
int i = 0;
cout << "Please enter a positive integer - no more than 20 digits: ";
cin.get(change);
if (change == '\n')
cin.get(change);
while (isdigit(change) && i < MAXIMUM_DIGITS)
{
digit[i] = change;
i++;
cin.get(change);
}
size_of_A = i;
int j = 0;
//convert ASCII values to actual values with while-loop
while (i > 0)
{
i--;
a[j] = digit[i] - '0';
j++;
}
}
//define output for the big integer with a for-loop to display each digit
void output_Large_Int(int a[], int size_of_A)
{
for (int i = 0; i < size_of_A; i++)
cout << a[size_of_A - i - 1];
}
void add(int a[], int size_of_A, int b[], int size_of_B, int sum[], int &size_Sum)
{
int i;
for(i = 0; i < MAXIMUM_DIGITS - 1; i++)
{
sum[i] = (a[i] + b[i]) % 10;
sum[i + 1] = (a[i] + b[i]) / 10;
i++;
}
if ((a[i] + b[i])/20 > 0)
{
cout << "INTEGER OVERFLOW in the sum, NOT accurate.\n"
<< endl;
}
|