Problem Solving: Calculator Using the if and switch Statement

In this lesson, we will think of a solution together to write a program that takes two operands with one operator and prints results.

A simple calculator program

Write and run a program that simulates a simple calculator. It should read two integers and a character. If the character is a +, the sum will be printed; if it is a -, the difference will be printed. If it is a *, the product will be printed. If it is a /, the quotient will be printed. If it is a %, the remainder will be printed.

Sample Input

5 * 5

Sample output

25

To write a program for the above problem, we need two integer numbers and a character operand to perform this task.

Let’s say we have three variables, one is num1 which stores the first operand, the second is num2, which stores the second operand and the last one is symbol which stores the operator.

This is what we have so far:

Press + to interact
...
int num1,num2,result;
char symbol;
cin >> num1 >> symbol >> num2;// taking two numbers and an operator symbol as input
...

How do we perform different operations in the program? Should we compare each operator using the if, if-else, or switch statement? We’ll implement the program using all three and see which implementation is better through animation as well.

Implementation 1: The if statement

After having the two operands (num1 and num2) and an operator (symbol), we will do the following:

  1. We’ll use the if statement to compare the symbol with +, -, *, / and %.
  2. We’ll then check if the statement is true. If it is, then perform the given operation on the operand and store the result in the result variable.
  3. We then print the result on the console.

Let’s see what we have so far:

Press + to interact
...
if (symbol == '+') // statement will be true if input symbol is +
result = num1 + num2;
if (symbol == '-') // statement will be true if input symbol is -
result = num1 - num2;
if (symbol == '*') // statement will be true if input symbol is *
result = num1 * num2;
if (symbol == '/') // statement will be true if input symbol is /
result = num1 / num2;
if (symbol == '%') // statement will be true if input symbol is %
result = num1 % num2;
...

Now, let’s write the complete code below and run it to see the output:

#include <iostream>
using namespace std;

int main()
{
    int num1,num2,result;
    char symbol;
    cout << "Num1 " << "Symbol " << "Num2 " << endl;
    cin >>  num1 >> symbol >> num2; // taking input expression 

    if (symbol == '+') // statement will be true if input symbol is +
         result = num1 + num2;
    if (symbol == '-') // statement will be true if input symbol is *
         result = num1 - num2;
    if (symbol == '*') // statement will be true if input symbol is *
         result = num1 * num2;
    if (symbol == '/') // statement will be true if input symbol is /
         result = num1 / num2;
    if (symbol == '%') // statement will be true if input symbol is %
         result = num1 % num2;

    cout<<"Result:"<<result<<endl;

    return 0;
}




Calculator using if statement

Let’s solve the quiz on the if statement:

Quiz

1

For 2+4, how many if conditions will be checked in the above program?

A)

5

B)

1

Question 1 of 20 attempted

What if the user enters an invalid input?

In case of the wrong symbol as input, it will not print some random value as the result. For example, if we input 1$ 1, it should print an invalid symbol. How can we solve this problem? Is there a more efficient way to solve this problem that takes less time than the if statement?

If you’re thinking of if-else, then congratulations on getting the correct answer! We could simply use an if-else to write this program.

Implementation 2: The if-else statement

In the if-else statement, we have multiple conditions to compare symbol with +, -, *, /, and %. If the first condition of + is true, it will skip the else part. In the same way, if the first condition of + is false, it will check the second condition. If the second condition of - is true, it will skip the else part of the program. In this way, it will save time, and this is a more efficient way than the if statement.

So what changes do we need to make to the program? We will change the above program with else-if and else.

Let’s see what changes we have made:

#include <iostream>
using namespace std;

int main()
{
    int num1,num2,result;
    bool isValid = true;
    char symbol;
    cout << "Num1 " << "Symbol " << "Num2 " << endl;
    cin >>  num1 >> symbol >> num2; // taking input expression 

    if (symbol == '+')// statement will be true if input symbol is +
        result=num1+num2;
    else if (symbol == '-')// statement will be true if input symbol is -
        result=num1-num2;
    else if (symbol == '*')// statement will be true if input symbol is *
        result=num1*num2;
    else if (symbol == '/')// statement will be true if input symbol is /
        result=num1/num2;
    else if (symbol == '%')// statement will be true if input symbol is %
        result=num1%num2;
    else // else statement will be true if all conditions will be false
    {
        cout<<"Invalid input"<<endl;
        isValid = false;
    }    
    if(isValid) // result should only be printed if the operation was valid
        cout<<num1<<symbol<<num2<<"="<<result<<endl;
    return 0;
}





Calculator using if-else

Let’s move towards the quiz on the if-else statement:

Quiz

1

For 4-2, how many if or else-if conditions will be checked in the program?

A)

5

B)

2

Question 1 of 20 attempted

The above solution is better than our first solution. However, in the worst-case scenario, we see that if the symbol is %, the last if condition would be true but all if conditions before it would also be checked.

Do you think that we can solve the same problem with an even more efficient method that takes less time than if-else?

If you’re thinking of a switch statement, then yes, we could just use a switch statement to write this program! Let’s see how.

Implementation 3: The switch statement

In the switch statement, we have multiple cases to compare symbol with +, -, *, / and %. If the symbol is %, it will take constant time to print the result for addition. It will not execute all cases to check whether it is % or something else. On the other hand, if we take the same case of % using if-else, it will check all the above statements. In that case, if-else will take the same execution time as the if statement.

Let’s see what changes we have made:

#include <iostream>
using namespace std;

int main()
{
    int num1,num2,result;
    char symbol;
    cout << "Num1 " << "Symbol " << "Num2 " << endl;
    cin >>  num1 >> symbol >> num2;

    switch(symbol)
    {
    case '+': // case will print sum if input symbol is +
        result=num1+num2;
        break;
    case '-': // case will print subtraction if input symbol is -
        result=num1-num2;
        break;
    case '/': // case will print division if input symbol is /
        result=num1/num2;
        break;
    case '%': // case will print mod if input symbol is %
        result=num1%num2;
        break;
    case '*': // case will print multiplication if input symbol is *
        result=num1*num2;
        break;
    default: // default will be execute in case of wrong input
        cout << "invalid symbol." << endl;
    }
    cout<<result<<endl;
    return 0;
}





Calculator using switch statement

Let’s move towards the quiz on the switch statement:

Quiz

1

For 2+2, what will be the output if we remove break statement in line 15 from case '+'?

A)

4

B)

0

Question 1 of 20 attempted

Visualizing conditional statements

Notice how we can solve the same problem with different methods with slight syntax changes.

We started with only if statements but then moved to a more efficient solution using if-else statements. However, the solution with if-else statements was not efficient in the worst scenario as discussed above. Therefore, we performed the same task with the switch statement that takes constant time in execution.

Exercise: How to handle invalid operations?

Modify Implementation 3 in the editor below such that if the user enters a wrong operation, the program should keep prompting for input until the user enters the correct input before displaying the result.

#include <iostream>
using namespace std;

int main()
{
    int num1,num2,result;
    char symbol;



    // Write your code here.
    
    






    // Your code at this point should ensure that the
    // "result" must have the required answer
    
    cout << "\n\n_____________________\n\n";
    cout<<num1<<symbol << num2<<"="<<result<<endl;
    cout << "\n_____________________\n";
    return 0;
}





Calculator using switch statement