How to design a simple calculator using C ?



We  can design a program with simple algorithms  to work as a calculator.Here we can perform five operations including addition , subtraction , modulus , multiplication , division.

Following concepts are used here :

  • simple input/output functions (eg. printf , scanf etc)
  • switch case
  • break               
SOURCE CODE :-

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

Comments

Popular Posts