Write a simple calculator program in C C++ using switch case

Write a simple calculator program in C C++ using switch case

Switch statement और multibranching statements के बारे में अधिक जानने के लिए देखें—Switch statements in C

Looping और iterative statements के बारे में और अधिक जानने के लिए देखें— Looping statements in C

Flowchart of simple calculator program using switch case

Simple calculator flowchart

Simple calculator program in C using switch case

#include<stdio.h>
int main()
{
    char choice;
    int n1,n2,res;
    printf("Enter choice: ");
    scanf("%c",&choice);
    printf("Enter two numbers: ");
    scanf("%d%d",&n1,&n2);
    switch(choice)
    {
        case '+':
        res=n1+n2;
        break;
        case '-':
        res=n1-n2;
        break;
        case '*':
        res=n1*n2;
        break;
        case '/':
        res=n1/n2;
        break;
        case '%':
        res=n1%n2;
        break;
        default:
        printf("Invalid choice");
    }
    printf("Result = %d",res);
    return 0;
}

Simple calculator program in C++ using switch case

#include<iostream>
using namespace std;
int main()
{
    char choice;
    int n1,n2,res;
    cout<<"Enter choice: ";
    cin>>choice;
    cout<<"Enter two numbers: ";
    cin>>n1>>n2;
    switch(choice)
    {
        case '+':
        res=n1+n2;
        break;
        case '-':
        res=n1-n2;
        break;
        case '*':
        res=n1*n2;
        break;
        case '/':
        res=n1/n2;
        break;
        case '%':
        res=n1%n2;
        break;
        default:
        cout<<"Invalid choice";
    }
    cout<<"Result = "<<res;
    return 0;
}

Output of simple calculator program in C C++ using switch case

Enter choice: +
Enter two numbers: 4 6
Result = 10
Enter choice: %
Enter two numbers: 10 6
Result = 4
Enter choice: #
Enter two numbers: 2 3
Invalid choice
Result = -53446 

Other switch case programs and branching programs in C C++

  1. Absolute value of number (simple if)
  2. Checking odd or even number (if else)
  3. Checking leap year (if else)
  4. Greater in two numbers (if else)
  5. Finding grade from percent (else if ladder)
  6. Total percent and division (else if ladder)
  7. Greatest in three numbers (nested if)
  8. Switch between Mon to Sun (switch case single case)
  9. Checking vowel or consonant (switch case multiple case)
  10. Number of days in a month (switch case multiple case)
  11. Unconditional Branching (break continue and goto)
Share it to:

Published by

admin

I am a computer teacher, programmer and web developer