Home / Programs / C Program to Make a Simple Calculator Using switch case
Programming Example

C Program to Make a Simple Calculator Using switch case

👁 1,601 Views
💻 Practical Program
📘 Step by Step Learning
Looking to create a simple calculator program in C? Look no further! Our step-by-step guide will walk you through the process of creating a basic calculator program in C. With our easy-to-follow instructions, you'll have a working calculator in no time. Whether you're new to programming or just looking for a fun project, this guide is perfect for you!

Program Code

// Performs addition, subtraction, multiplication or division depending the input from user

# include <stdio.h>

int main() {

    char operator;
    double firstNumber,secondNumber;

    printf("Enter an operator (+, -, *,): ");
    scanf("%c", &operator);

    printf("Enter two operands: ");
    scanf("%lf %lf",&firstNumber, &secondNumber);

    switch(operator)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber + secondNumber);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber - secondNumber);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber / secondNumber);
            break;

        // operator doesn't match any case constant (+, -, *, /)
        default:
            printf("Error! operator is not correct");
    }
    
    return 0;
}

Output

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

Explanation

The * operator entered by the user is stored in the operator variable. And, the two operands, 1.5 and 4.5 are stored in variables firstNumber and secondNumber respectively.

Since, the operator * matches the case case '*':, the control of the program jumps to

printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber);

This statement calculates the product and displays it on the screen.

Finally, the break; statement ends the switch statement.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.