/* CSE 351 Section 03 * * calculator.c * * Provide two operands and an operator, and this program will print the * output of that operation. * * Usage: ./calculator, then use stdin to provide integer, integer, operator * arguments when the program prompts for them. * Operator can be one of [+,-,/,x,%] and the operands are integers * * Notes: * * => scanf() is used to take in arguments, read more on the documentation here: * => http://en.cppreference.com/w/cpp/io/c/fscanf * => http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf * * => function prototype above main() tells compiler the return type and params of print_operation() * => could have also just declared the entire function above main() * => neglecting to do either will result in a compilation error * * => this program does not rigorously check for input errors nor does it hand exceptions * */ #include #include void print_operation(int a, int b, char operator); int main(int argc, char **argv) { /* scanf() takes in arguments from stdin and stores them according to the parameter * format in the locations pointer to by additional arguments. * The additional arguments should point to already allocated objects of the type * specified by their corresponding format specifier within the format string. * */ // Set up argument locations int a; int b; char operator[1]; printf("num 1: "); scanf("%d", &a); /* <-- %d is format, &a is location. */ printf("num 2: "); scanf("%d", &b); printf("operator: "); scanf(" %c", operator); /* <-- space in front of %c is important*/ print_operation(a, b, operator[0]); return 0; } /* Prints out the result when the operator is applied to the * operands a and b. Supports addition (+), subtraction (-), * division (/), multiplication (x), and modulus (%) */ void print_operation(int a, int b, char operator) { int result = 0; switch (operator) { case '+': result = a + b; break; case '-': result = a - b; break; case '/': result = a / b; break; case 'x': result = a * b; break; case '%': result = a % b; break; default: printf("Invalid operator"); return; } printf("%d %c %d = %d\n", a, operator, b, result); }