#include #include #include #include // converts a string representation of a positive integer into an int. ignores // spaces that are within the string int parse_int(const char *expr) { int result = 0; int place_value = 1; // process digits by iterating through chars of `expr` right to left for (int i = strlen(expr) - 1; i >= 0; i--) { char ch = *(expr + i); if (ch == ' ') { continue; } int digit = ch - '0'; result += place_value * digit; place_value *= 10; } return result; } // recursively evaluates an arithmetic expression // evaluates + and - after * and / to respect order of operations. // evaluates + and - left to right, * and / left to right to respect order of // operations. int eval_expr(const char *expr) { int expr_len = strlen(expr); // look for any addition or subtraction operators first for (int i = 0; i < expr_len; i++) { char op = *(expr + i); if (op == '+' || op == '-') { char *lhs = malloc((i + 1) * sizeof(char)); char *rhs = malloc((expr_len - i) * sizeof(char)); // split the expression into left and right operands strncpy(lhs, expr, i); lhs[i] = '\0'; // strncpy might not end new string with null terminator? strcpy(rhs, expr + i + 1); int answer; if (op == '+') { answer = eval_expr(lhs) + eval_expr(rhs); } else if (op == '-') { answer = eval_expr(lhs) - eval_expr(rhs); } free(lhs); free(rhs); return answer; } } // look for multiplication and division once theres no addition or // subtraction, this makes them get evaluated first due to the nature of // recursion. for (int i = 0; i < expr_len; i++) { char op = *(expr + i); if (op == '*' || op == '/') { char *lhs = malloc((i + 1) * sizeof(char)); char *rhs = malloc((expr_len - i) * sizeof(char)); // split the expression into left and right operands strncpy(lhs, expr, i); lhs[i] = '\0'; // strncpy might not end new string with null terminator? strcpy(rhs, expr + i + 1); int answer; if (op == '*') { answer = eval_expr(lhs) * eval_expr(rhs); } else if (op == '/') { answer = eval_expr(lhs) / eval_expr(rhs); } free(lhs); free(rhs); return answer; } } // no more operators remain, so expression must be a standalone positive // integer expression, which we convert to an int return parse_int(expr); } int main() { char expression[1000]; printf("Enter an arithmetic expression (integers with +, -, *, /): "); // read the expression if (fgets(expression, sizeof(expression), stdin) != NULL) { // remove newline if present int len = strlen(expression); if (len > 0 && expression[len - 1] == '\n') { expression[len - 1] = '\0'; len = len - 1; } printf("Input: %s\n", expression); int result = eval_expr(expression); printf("Output: %d\n", result); } return 0; }