Challenge
Write a program that can perform mathematical operations on two or more numbers (up to four) like the calculator.
Requirement
- The calculator should support should addition, multiplication and subtraction operations (operators).
- The input numbers (operands) would be positive whole numbers > 0 i.e. (1,2,3....) and < 9999
- A minimum of two operands and one operator per expression will be provided as input.
- A maximum of four operands with a maximum of three operators can be in the input expression.
- An operator will not repeat again in the expression .e.g. 2+3+5 is not valid input as the operator (+) repeats twice in the expression. However, if your code can handle such expression it's even better.
- Follow operator precedence rules while evaluating the expressions (multiplication, addition, subtraction).
- All input will be provided correctly, so data validation is not expected.
Test cases
Based on the operator (+ , - , * ) perform the correct mathematical operation on the operands.
Test cases
No. | Expression (Input) | Result (Output) | Explanation |
---|---|---|---|
1 | 5+1 | 6 | |
2 | 10*2 | 20 | |
3 | 15+2-3 | 10 | |
4 | 20*2+5 | 45 | Perform multiplication first, then add. |
5 | 20-10*2 | 10 | Perform multiplication first, then add. |
6 | 20-10*2+5 | 5 | Perform the multiplication first, followed by addition and then subtraction. |
Instructions
- Accept the mathematical expression to evaluate as a single input argument to the program.
- Evaluate the input express and display the result.
Next Level
If you are able to solve this challenge, move up next level of Advance Line Expression Calculator.