#include using namespace std; struct Vector { int * v; int size; // actual current size of the internal array int num; // how many ints are actually stored in it Vector() // no return type, same name as object = CONSTRUCTOR { size = 0; num = 0; v = new int[0]; } // Functions inside an object are called METHODS void setsize(int sz) { if (sz < 0) { cout << "Can't create an array of size " << sz << "\n"; exit(1); } int * temp = new int[sz]; int amt = min(size, sz); for (int i = 0; i < amt; i += 1) temp[i] = v[i]; delete v; // without this we had a MEMORY LEAK v = temp; size = sz; } int getsize() { return size; } int & access(int pos) { if (pos < 0) { cout << "Index to array is out of bounds\n"; exit(1); } if (pos >= size) setsize(pos + 1); return v[pos]; } void push(int x) { access(num) = x; num += 1; } int pop() // adding push and pop makes this vector into a STACK { num -= 1; return access(num); } }; bool looks_like_an_int(string s) { for (int i = 0; i < s.length(); i += 1) if (s[i] < '0' || s[i] > '9') return false; return true; } int convert_string_to_int(string s) { int sofar = 0; for (int i = 0; i < s.length(); i += 1) sofar = sofar * 10 + s[i] - '0'; return sofar; } struct Input { string s; int pos; Input(string x) { s = x + " "; pos = 0; } void take(string x) { s = x + " "; pos = 0; } string get() { // example: // s = "1 x 7363 * + ." // pos = 3 while (s[pos] == ' ') pos += 1; string result = ""; while (s[pos] != ' ') { result += s[pos]; pos += 1; } return result; } }; void evaluate(string formula, int x) { Input in(formula); Vector R; while (true) { string part = in.get(); if (part == "x") R.push(x); else if (part == ".") { cout << "Result is " << R.pop() << "\n"; break; } else if (looks_like_an_int(part)) R.push(convert_string_to_int(part)); else if (part == "+") { int second = R.pop(); int first = R.pop(); R.push(first + second); } else if (part == "-") { int second = R.pop(); int first = R.pop(); R.push(first - second); } else if (part == "*") { int second = R.pop(); int first = R.pop(); R.push(first * second); } else if (part == "/") { int second = R.pop(); int first = R.pop(); if (second == 0) { cout << "division by zero\n"; exit(1); } R.push(first / second); } else { cout << "error '" << part << "' in formula\n"; exit(1); } } } int main() { cout << "Enter a range for x: "; int xmin, xmax; cin >> xmin >> xmax; cout << "Enter the formula: "; string formula; getline(cin, formula); // to absorb the enter after x getline(cin, formula); for (int x = xmin; x <= xmax; x += 1) evaluate(formula, x); }