C Program to Create Simple Calculator Using Switch Case

1. Introduction

A calculator performs basic arithmetic operations like addition, subtraction, multiplication, and division. In this post, we'll develop a simple calculator in C using the switch case statement to handle different arithmetic operations.

2. Program Overview

The program will:

1. Display a menu for the user to choose an arithmetic operation.

2. Get the choice from the user.

3. Ask the user to input two numbers.

4. Based on the choice, perform the desired arithmetic operation using a switch case.

3. Code Program

#include <stdio.h>

int main() {
    int num1, num2, choice;
    double result;

    // Displaying menu
    printf("Menu:\n");
    printf("1. Add\n");
    printf("2. Subtract\n");
    printf("3. Multiply\n");
    printf("4. Divide\n");
    printf("Enter your choice (1-4): ");
    scanf("%d", &choice);

    // Getting numbers from the user
    printf("Enter two integers: ");
    scanf("%d%d", &num1, &num2);

    // Performing the operation based on user's choice
    switch (choice) {
        case 1:
            result = num1 + num2;
            break;
        case 2:
            result = num1 - num2;
            break;
        case 3:
            result = num1 * num2;
            break;
        case 4:
            if (num2 != 0)
                result = (double) num1 / num2;
            else {
                printf("Error! Division by zero is not allowed.\n");
                return 0;
            }
            break;
        default:
            printf("Invalid choice.\n");
            return 0;
    }
    printf("Result: %.2lf\n", result);

    return 0;
}

Output:

For a choice of 1 (Add) and numbers 5 and 6, the program would output:
Result: 11.00

4. Step By Step Explanation

1. We begin by displaying a menu of operations that the calculator can perform.

2. We then get the user's choice and store it in the choice variable.

3. Next, we prompt the user to input two integer numbers. These numbers will be used for our calculations.

4. The switch case is then utilized to check the user's choice. Depending on the choice, an arithmetic operation is performed:

- case 1: Adds the two numbers.

- case 2: Subtracts the second number from the first.

- case 3: Multiplies the two numbers.

- case 4: Divides the first number by the second. Here, we also have an error check to ensure that we don't divide by zero, as this would lead to an undefined result.

5. If the user inputs a choice outside of the range 1-4, the program displays "Invalid choice" and terminates.

6. Finally, the program displays the result of the arithmetic operation.

Note: For the division operation, we type-cast one of the integers to double to get a precise result.

Comments