Example 1: Simple Calculator with if..else if...else
Output
Enter operator ( either +, -, * or / ): * Enter first number: 3.4 Enter second number: 5.6 3.4 * 5.6 = 19.04
In the above example, the user is prompted to enter an operator (either +, -, * or /) and two numbers.
The parseFloat() converts the numeric string value to a floating-point value.
The if...else if...if statement is used to check the condition that the user has entered for the operator. The corresponding operation is performed and the output is displayed.
Example 2: Simple Calculator with switch
Output
Enter operator: + Enter first number: 4 Enter second number: 5 4 + 5 = 9
In above program, the user is asked to enter either +, -, * or /, and two numbers. Then, the switch statement executes cases based on the user input.