Banner Header

Thursday 7 September 2017

C Program to Make a Simple Calculator Using switch...case

C Program to Make a Simple Calculator Using switch...case

Example to create a simple calculator to add, subtract, multiply and divide using switch and break statement.




This program takes an arithmetic operator +, -, *, / and two operands from the user and performs the calculation on the two operands depending upon the operator entered by the user.

Example: Simple Calculator using switch Statement


// Performs addition, subtraction, multiplication or division depending the input from user
#include <stdio.h>
#include <conio.h>
int main() {
    char oper;
    double firstNumber,secondNumber;
    printf("Enter an operator (+, -, *,): ");
    scanf("%c", &oper);
    printf("Enter two operands: ");
    scanf("%lf %lf",&firstNumber, &secondNumber);
    switch(oper)
    {
        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");
    }
    printf("\nSubscribe My Channel");
    return 0;
 
getch();
}
Output
Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8
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.

Click on the download button to download file

                                                     download button

C Program to Make a Simple Calculator Using switch...case Reviewed by Waqas Ahmed Mir PC on September 07, 2017 Rating: 5 C Program to Make a Simple Calculator Using switch...case Example to create a simple calculator to add, subtract, multiply and divide usi...

No comments: