Home » C solved programs » C switch case programs

C program to design calculator with basic operations using switch

This program will read two integer numbers and an operator like +,-,*,/,% and then print the result according to given operator, it is a complete calculator program on basic arithmetic operators using switch statement in c programming language.

Calculator program with Basic operations using switch



/*C program to design calculator with basic operations using switch.*/
 
#include <stdio.h>
 
int main()
{
    int num1,num2;
    float result;
    char ch;    //to store operator choice
     
    printf("Enter first number: ");
    scanf("%d",&num1);
    printf("Enter second number: ");
    scanf("%d",&num2);
     
    printf("Choose operation to perform (+,-,*,/,%): ");
    scanf(" %c",&ch);
     
    result=0;
    switch(ch)    
    {
        case '+':
            result=num1+num2;
            break;
             
        case '-':
            result=num1-num2;
            break;
         
        case '*':
            result=num1*num2;
            break;
             
        case '/':
            result=(float)num1/(float)num2;
            break;
             
        case '%':
            result=num1%num2;
            break;
        default:
            printf("Invalid operation.\n");
    }
 
    printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
    return 0;
}

Output

    First run:
    Enter first number: 10
    Enter second number: 20 
    Choose operation to perform (+,-,*,/,%): +
    Result: 10 + 20 = 30.000000 

    Second run:
    Enter first number: 10
    Enter second number: 3
    Choose operation to perform (+,-,*,/,%): /
    Result: 10 / 3 = 3.333333 

    Third run:
    Enter first number: 10
    Enter second number: 3
    Choose operation to perform (+,-,*,/,%): >
    Invalid operation.
    Result: 10 > 3 = 0.000000 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.