C program for Simple Calculator using Switch Case Statement

The below code will create a simple calculator with the Switch structure;

Logic: 
Each case is designed to work with a specific switch, in this case  switches are the   mathematical operators i.e " +, - , * , / , % (for remainder-modulus) ". 

Code: 
#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a,b,mod;
    float sum,sub,mul,div,x,y;
    char ch,op;

        printf("This is a calculator...\nThe following operations can be performed\n\naddition +\nsubtration -\nmultiplication *\ndivision /\nremainder %%\n\nEnter you equation e.g \"3+5\" :");
        scanf("%f %c %f",&x, &op, &y);

        switch(op)
        {
        case '+':
            sum=x+y;
            printf("answer is %.1f",sum);
            break;
         case '-':
            sub=x-y;
            printf("answer is %.1f",sub);
            break;
         case '*':
            mul=x*y;
            printf("answer is %.1f",mul);
            break;
         case '/':
            if(x==0||y==0)
                {
                    printf("The entered value must not be zero");
                    break;
                }

            div=x/y;
            printf("answer is %.2f",div);
            break;
         case '%':
            a=x;
            b=y;
            mod=a%b;
            printf("answer is %d",mod);
            break;
         default:
            printf("incorrect input");

        }
        printf("\n\n(*_*) Would you like to run again...(Y/N)");
        scanf(" %c", &ch);
        if(ch=='Y'||ch=='y')
            {
                system("cls");
                main();
            }
        printf("\npress any key to continue:");
        getch();
    }
 

Post a Comment

CodeNirvana
Newer Posts Older Posts
© Copyright Encyclopedia of C | Designed By Code Nirvana
Back To Top