APCSPCODE
APCSPCODE
1 #include <bits/stdc++.h>
2 using namespace std;
3
4 int calculate(vector<int> nums, vector<char> operators) {
5 int result = nums[0];
6 for (int i = 0; i < operators.size(); i++) {
7 char operat = operators[i];
8 int num2 = nums[i + 1];
9
10 if (operat == '+') {
11 result += num2;
12 } else if (operat == '-') {
13 result -= num2;
14 } else if (operat == '*') {
15 result *= num2;
16 } else if (operat == '/') {
17 if (num2 != 0) {
18 result /= num2;
19 } else {
20 cout << "Error: Division by zero" << endl;
21 return 0;
22 }
23 } else {
24 cout << "Error: Invalid operator " << operat << endl;
25 return 0;
26 }
27 }
28 return result;
29 }
30
31 int main() {
32 vector<char> validOperators = {'+', '-', '*', '/'};
33 vector<int> nums;
34 vector<char> usingOperators;
35
36 string line;
37 cout << "Enter a simple expression (e.g., 3+4*2): ";
38 getline(cin, line);
39
40 for (char value : line) {
41 if (isdigit(value)) {
42 nums.push_back(value - '0');
43 } else if (find(validOperators.begin(), validOperators.end(), value) != validOperators.end()) {
44 usingOperators.push_back(value);
45 }
46 }
47
48 int result = calculate(nums, usingOperators);
49
50 cout << "\nSteps:\n";
51 int tempResult = nums[0];
52 for (int i = 0; i < usingOperators.size(); i++) {
53 char operat = usingOperators[i];
54 int num2 = nums[i + 1];
55 cout << "(" << i + 1 << ") " << tempResult << " " << operat << " " << num2;
https://bakerfranke.github.io/codePrint/ Page 1 of 2
12/18/24, 9:14 AM
https://bakerfranke.github.io/codePrint/ Page 2 of 2