Question

Write a program in C to create a simple calculator using the switch statement.

Updated on May 31, 2025 | By Learnzy Admin | 👁️ Views: 287 students

Solution
✔ Verified

This program is a simple calculator written in C that performs basic arithmetic operations such as addition, subtraction, multiplication, and division. It uses a switch statement to select the operation based on the user's choice. The user is prompted to enter two numbers and an operator. Depending on the operator entered (+, -, *, /), the corresponding case in the switch statement is executed, and the result is displayed. If an invalid operator is entered, the program notifies the user accordingly.

#include <stdio.h>

int main() {
    char op;
    float num1, num2;

    printf("Enter an operator (+, -, *, /): ");
    scanf(" %c", &op);
    printf("Enter two numbers: ");
    scanf("%f %f", &num1, &num2);

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

    return 0;
}

Output -

Enter an operator (+, -, *, /): +
Enter two numbers: 23
89
Result = 112.00

 

Was this solution helpful? 27
Click here to download practice questions on Switch statement in C

More Questions on Switch statement in C

Question 1

Write a C program to check if the entered character is a vowel or consonant using a switch statement.


View solution
Question 2

Write a C program to find the day of the week based on an input number using a switch statement


View solution