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
|
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void initialize(int digits[], int size);//initializes all elements, sets everything to '0'
void addition(int digits1[], int digits2[], int size);//add elements of the arrays
void subtraction(int digits1[], int digits2[], int size);//subtract elements of the arrays
void display(int digits[], int size);//displays the array
int main()
{
string number1;
string number2;
char math;
while (true) {
cout << "Enter an expression:\n";
cin >> number1 >> math >> number2;
//check for sentintal
if (number1 == "0" && math == '%' && number2 == "0") {
break;
return 0;
}
const int SIZE = 20;
int digits1[SIZE];
int digits2[SIZE];
//sets all values in both arrays to '0'
initialize(digits1, SIZE);
initialize(digits2, SIZE);
//takes the characters of the inputted string and places them into the arrays
for (int i = 0; i < number1.length(); i++) {
digits1[SIZE - (i + 1)] = number1[number1.length() - (i + 1)] - '0';
}
for (int i = 0; i < number2.length(); i++) {
digits2[SIZE - (i + 1)] = number2[number2.length() - (i + 1)] - '0';
}
//conditional operations
if (math == '+') {
addition(digits1, digits2, SIZE);
display(digits1, SIZE);
cout << endl;
}
else if (math == '-') {
subtraction(digits1, digits2, SIZE);
display(digits1, SIZE);
cout << endl;
}
else {
cout << "Invalid Operator\n";
return 0;
}
}
return 0;
}
void initialize(int digits[], int size) {
for (int i = 0; i < size; i++) {
digits[i] = 0;
}
}
void addition(int digits1[], int digits2[], int size) {
for (int i = size - 1; i > 0; --i) {
int sum = digits1[i] + digits2[i];
if (sum >= 10) {
digits1[i - 1]++;
sum = sum - 10;
}
digits1[i] = sum;
}
}
void subtraction(int digits1[], int digits2[], int size) {
for (int i = size - 1; i > 0; --i) {
int difference = digits1[i] - digits2[i];
if (difference < 0) {
digits1[i - 1]--;
difference = difference + 10;
}
digits1[i] = difference;
}
}
void display(int digits[], int size) {
for (int i = 0; i < size; i++) {
cout << digits[i] << ' ';
}
}
| |