Calculator program in c

Calculator program in c is simple and easy program in c.

In this tutorial, we will see a simple program which is to implement calculator program in c.

How to implement calculator program in c

We know the simple mathematical operation. Using switch case we can implement calculator.  Means whenever a user wants to calculate any operation its search for a case with operation and perform the mathematical operation.

We write first cases with the mathematical operation and write corresponding code in case.

Next, We take input operation from the user  (addition,  divide )

Search input in switch cases. The corresponding case matches then that case will get executed.

User got the result of an operation.

Calculator program in c using switch case

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990#include<stdio.h>main(){char choice;float num1,num2,result;int flag=1;printf(“Enter +,-,/,* for knowing the result\n”);scanf(“%c”,&choice);printf(“Enter number 1\n”);scanf(“%f”,&num1);printf(“Enter number 2\n”);scanf(“%f”,&num2);switch(choice){case ‘+’:result=num1+num2;break;case ‘-‘:result=num1-num2;break;case ‘/’:{if(num2==0){flag=0;}else{result=num1/num2;}break;}case ‘*’: result=num1*num2;break;default:printf(“Error”);break;}if(flag==1){printf(“%f %c %f = %f”,num1,choice,num2,result);}else{printf(“%f %c %f = undefined\n”,num1,choice,num2);}}

Output:

Calculator program in c

Calculator program in c
Calculator program in c

Explanation

1. Program starts with initializing

choice → For storing the operators like +,-,/,*

num1,num2 → For storing two integers

result → For storing the resulting value

flag → To store true or false.

2. First, we take a choice of the user (+,-,/,*) then the two numbers.

3.Now we use switch case

If the user enters ‘+’ as his choice then the result will be result=num1+num2

next If the user enters ‘-‘ as his choice then the result will be result=num1-num2

If the user enters ‘/’ as his choice then the result will be result=num1/num2 if num2 is not zero else flag will be zero and the output would be undefined

If the user enters ‘*’ as his choice then the result will be result=num1*num2