Creating Simple Calculator in C programming using switch statement.




  •  Creating Simple Calculator in C programming using switch statement.



#include <stdio.h>

int main() {
    char operator;
    double n1, n2;

    printf("Enter an operator (+, -, *, /) : ");
    scanf("%c", &operator);
    printf("Enter two operands : ");
    scanf("%lf %lf",&n1, &n2);

    switch(operator)
    {    
        case '+':
            printf("%.2lf + %.2lf = %.2lf",n1, n2, n1+n2);
            break;

        case '-':
            printf("%.2lf - %.2lf = %.2lf",n1, n2, n1-n2);
            break;

        case '*':
            printf("%.2lf * %.2lf = %.2lf",n1, n2, n1*n2);
            break;

        case '/':
            printf("%.2lf / %.2lf = %.2lf",n1, n2, n1/n2);
            break;

        // If operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! Enter the correct operator and try again.");
    }

    return 0;
}

OUTPUT

Enter an operator (+, -, *,) : +
Enter two operands: 25.00
30.00
25.00 + 30.00 = 55.00





EXPLANATION


1. The operator  entered by user is get stored in the operator variable.

2. The two operands 25.00 and 30.00 get stored in the two variables n1, n2 respectively.

3. As the operator is  the , the control program jumps to case '+':   

 printf("%.2lf + %.2lf = %.2lf", n1,n2, n1+n2); 

4.  At last break statement terminates the switch statement.






Comments

Popular posts from this blog

ATM solution in C language.- Codechef

MOTIVATION SOLUTION IN C LANGUAGE | CODECHEF | IMDB

APPLE AND ORANGE | HACKERRANK | PROBLEM SOLVING | SOLUTION IN C