logo

UTK Notes


Lab 03: Calculator

Assignment

You will be creating a calculator that allows the user to enter two operands and an operation. Your program will then give the result.

Operands

The operands will be specified as integer numbers, so you must declare the appropriate data types. If your program is unable to input valid data from the user, output the following error prompt: “Invalid left operand.” or “Invalid right operand.”

Every operation will require two operands except for the “absolute value.”

Operations

The operation will be specified as a single character. The following operations are performed for the given characters:

1
2
3
4
5
6
A or a or +      - Adds left and right operands.
S or s or -      - Subtracts right from left operand.
M or m or x or * - Multiplies left and right operands.
D or d or /      - Divides left over right operand.
B or b or |      - Returns the absolute value of the left (and only) operand.
C or c or %      - Performs left operand modulo right operand.

If the user does not specify one of the above operands, output the following error prompt: “Unknown operation.”

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
./calc
Enter left operand: 10
Enter operation: *
Enter right operand: 3
Result = 30

./calc
Enter left operand: -77
Enter operation: B
Result = 77

./calc
Enter left operand: ZAMBY
Invalid left operand.

./calc
Enter left operand: 22
Enter operation: &
Enter right operand: 13
Unknown operation.

Restrictions

  1. You must NOT duplicate any code. If you notice that you’re writing the same statement, you need to rethink the flow of your code.
  2. You must use if statements to error check the user’s input, and you must use mutual exclusion where applicable (i.e., else if and/or else).
  3. You must use a SWITCH statement when determining which operation to perform. Your default case must be used to determine if an invalid operation was specified.
  4. You may not call any math functions (if you know how).
  5. Comments and good formatting are required.

Submission

Your code must compile and run on the Tesla machines, or it will not be graded! Submit your file as calc.cpp.

Hints

We will go over more uses of “cin” on Thursday, but listen to hints from your TAs! Try wrapping cin statements inside if statements for error checking.

cin.get() and cin.ignore() will also be helpful in gathering input.

If you type in “Asdfk” as an operator, the program will take the first character (‘A’) and decide if it’s a legitimate operation. (In this case, yes - ‘A’ would fall into the addition category).