Simple Calculator (switch): flowchart, algorithm and program

This program reads two numbers and an operator, then uses a switch on the operator to pick the right calculation and print the result. Division is guarded by a check so dividing by zero prints an error instead of a bad answer.

▶ Watch the dry run step by step →

Algorithm

  1. Step 1: Start.
  2. Step 2: Read a.
  3. Step 3: Read op.
  4. Step 4: Read b.
  5. Step 5: If op == '+', go to step 6; otherwise go to step 7.
  6. Step 6: Print a + b. Go to step 16.
  7. Step 7: If op == '-', go to step 8; otherwise go to step 9.
  8. Step 8: Print a - b. Go to step 16.
  9. Step 9: If op == '*', go to step 10; otherwise go to step 11.
  10. Step 10: Print a * b. Go to step 16.
  11. Step 11: If op == '/', go to step 12; otherwise go to step 15.
  12. Step 12: If b == 0, go to step 13; otherwise go to step 14.
  13. Step 13: Print "Error: Division by zero". Go to step 16.
  14. Step 14: Print a / b. Go to step 16.
  15. Step 15: Print "Invalid operator".
  16. Step 16: Stop.

Pseudocode

BEGIN
    READ a
    READ op
    READ b
    IF op == '+' THEN
        PRINT a + b
    ELSE
        IF op == '-' THEN
            PRINT a - b
        ELSE
            IF op == '*' THEN
                PRINT a * b
            ELSE
                IF op == '/' THEN
                    IF b == 0 THEN
                        PRINT "Error: Division by zero"
                    ELSE
                        PRINT a / b
                    END IF
                ELSE
                    PRINT "Invalid operator"
                END IF
            END IF
        END IF
    END IF
END

Program in C, Python and Java

Simple Calculator (switch) program in C

#include <stdio.h>

int main() {
    float a, b;
    char op;

    printf("Enter first number: ");
    scanf("%f", &a);
    printf("Enter operator (+ - * /): ");
    scanf(" %c", &op);
    printf("Enter second number: ");
    scanf("%f", &b);

    switch (op) {
        case '+':
            printf("Result = %.2f\n", a + b);
            break;
        case '-':
            printf("Result = %.2f\n", a - b);
            break;
        case '*':
            printf("Result = %.2f\n", a * b);
            break;
        case '/':
            if (b == 0)
                printf("Error: Division by zero\n");
            else
                printf("Result = %.2f\n", a / b);
            break;
        default:
            printf("Invalid operator\n");
    }
    return 0;
}

Simple Calculator (switch) program in Python

a = float(input("Enter first number: "))
op = input("Enter operator (+ - * /): ")
b = float(input("Enter second number: "))

if op == '+':
    print("Result = {:.2f}".format(a + b))
elif op == '-':
    print("Result = {:.2f}".format(a - b))
elif op == '*':
    print("Result = {:.2f}".format(a * b))
elif op == '/':
    if b == 0:
        print("Error: Division by zero")
    else:
        print("Result = {:.2f}".format(a / b))
else:
    print("Invalid operator")

Simple Calculator (switch) program in Java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        float a = sc.nextFloat();
        System.out.print("Enter operator (+ - * /): ");
        char op = sc.next().charAt(0);
        System.out.print("Enter second number: ");
        float b = sc.nextFloat();

        switch (op) {
            case '+':
                System.out.printf("Result = %.2f%n", a + b);
                break;
            case '-':
                System.out.printf("Result = %.2f%n", a - b);
                break;
            case '*':
                System.out.printf("Result = %.2f%n", a * b);
                break;
            case '/':
                if (b == 0)
                    System.out.println("Error: Division by zero");
                else
                    System.out.printf("Result = %.2f%n", a / b);
                break;
            default:
                System.out.println("Invalid operator");
        }
    }
}

Sample input: a = 12, op = /, b = 4
Output: Result = 3.00

How it works

  • Read the first number into a, the operator into op, and the second number into b. Note the space in scanf(" %c", &op): it skips the leftover newline so the operator is read correctly.
  • switch (op) compares the character with each case: '+', '-', '*' and '/'. The matching case prints a+b, a-b, a*b or a/b with %.2f (two decimals).
  • Each case ends with break so execution doesn't fall through into the next case and print extra results.
  • In case '/', the program first checks if (b == 0). If true it prints "Error: Division by zero"; otherwise it prints a / b.
  • The default case runs when op matches none of the four, and prints "Invalid operator". For a = 12, op = '/', b = 4, the '/' case runs, b is not 0, and it prints Result = 3.00.

Dry run (trace table)

StepLineBoxaopbOutput
13Start
28Read a12
310Read op12'/'
412Read b12'/'4
515op == '+'?12'/'4
618op == '-'?12'/'4
721op == '*'?12'/'4
824op == '/'?12'/'4
925b == 0?12'/'4
1028Print a / b12'/'4Result = 3.00
1133Stop12'/'4

Time and space complexity

Time: O(1) · Space: O(1). The program does a fixed number of comparisons and one arithmetic operation regardless of input values.

Common mistakes

  • Writing scanf("%c", &op) without the leading space, so the newline left by the previous input is read as the operator and you get "Invalid operator".
  • Forgetting break after a case, which makes the program fall through and print the results of the following cases too.
  • Not checking b == 0 before dividing. With floats this gives inf instead of an error message, and with ints it crashes the program.
  • Using double quotes for the operator in a case, like case "+", instead of single quotes for a char, like case '+'.

Viva questions

Q1. Why do you write a space before %c in scanf(" %c", &op) on line 10?

After scanf("%f") reads the first number, the Enter key (newline) is still in the input buffer. The space in the format string tells scanf to skip that whitespace, so op gets the real operator and not '\n'.

Q2. Why did you declare a and b as float instead of int?

So the calculator can accept decimal numbers like 2.5 and give a correct fractional answer for division. With int, 5/2 would give 2 and decimals could not be entered.

Q3. What is the role of break in each case of the switch?

break stops execution after the matching case. Without it, control would fall through into the next cases and print several results.

Q4. What does the default case do, and when does it run?

It runs when op matches none of '+', '-', '*', '/', for example if the user types '%' or 'x'. It prints "Invalid operator".

Q5. Why is there an if (b == 0) check inside the '/' case? What would happen without it?

Dividing by zero is undefined in mathematics. With floats in C, a/0 would give inf or nan instead of a sensible answer, so the check prints an error message instead.

Q6. What happens if the user enters 0 as the first number with operator '/' and 5 as the second? And what if the second number is 0?

0 / 5 gives Result = 0.00, which is valid. If the second number is 0, the program prints "Error: Division by zero" and gives no result.

Q7. Why can't you use a switch on a float, and why is switch suitable here?

A switch works only on integer-type values (int, char, enum), not floats. Here the switch is on the char op, and a single character is compared against fixed constant cases, which is cleaner than a long if-else chain.

Q8. What is the time complexity of this program, and how does it change if you want to support more operators or the user to do repeated calculations?

It is O(1), because it does a fixed number of steps no matter what the input values are. To support more operators, add more case labels such as '%' (using integers or fmod). To allow repeated calculations, wrap the code in a loop like do-while that asks 'continue?' after each result.

Frequently asked questions

Why do we use switch instead of if-else in a calculator?

The choice depends on one value (the operator), so switch is cleaner to read than a long if-else chain. Python has no classic switch, so it uses if/elif for the same job.

What happens if the user divides by zero?

The check if (b == 0) catches it and the program prints "Error: Division by zero" without doing the division.

Why is there a space before %c in scanf?

The space tells scanf to skip whitespace, including the newline left in the input after the first number. Without it, op would capture that newline instead of the operator.

More programs

← All programs

Try AI Flowchart free →