c
  1. c-program-to-make-a-simple-calculator-using-switchcase

Program to Make a Simple Calculator Using switch...case - ( C Programs )

Heading

The program is designed to implement a simple calculator using switch...case statement in C programming language.

Example

#include <stdio.h>

int main()
{
    char operator;
    double operand1, operand2, result;

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

    printf("Enter operand1: ");
    scanf("%lf", &operand1);

    printf("Enter operand2: ");
    scanf("%lf", &operand2);

    switch(operator)
    {
        case '+':
            result = operand1 + operand2;
            printf("\n%.2lf + %.2lf = %.2lf", operand1, operand2, result);
            break;

        case '-':
            result = operand1 - operand2;
            printf("\n%.2lf - %.2lf = %.2lf", operand1, operand2, result);
            break;

        case '*':
            result = operand1 * operand2;
            printf("\n%.2lf * %.2lf = %.2lf", operand1, operand2, result);
            break;

        case '/':
            if(operand2 == 0)
            {
                printf("\nDivision by zero error");
            }
            else
            {
                result = operand1 / operand2;
                printf("\n%.2lf / %.2lf = %.2lf", operand1, operand2, result);
            }
            break;

        default:
            printf("\nInvalid operator");
    }

    return 0;
}

Output

Enter operator (+, -, *, /): *
Enter operand1: 7
Enter operand2: 9

7.00 * 9.00 = 63.00

Explanation

The program starts by asking the user to input the operator (+, -, *, or /) and the two operands that the user wants to perform the operation on. Then, the program utilizes a switch statement that takes the operator as input and determines which operation to perform on the two operands using the relevant case blocks. If the user enters an invalid operator, the program notifies the user of that error.

Use

This calculator program can be used to perform simple arithmetic operations on two operands.

Summary

In summary, this C program utilizes a switch statement to implement a simple calculator that can perform basic arithmetic operations (+, -, *, /) on two inputs from the user, then outputs the corresponding result.

Published on: