Examples of C part 42 simple Calculator

Program :
#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:
Enter +,-,/,* for knowing the result
*
Enter number 1
1234
Enter number 2
1234
1234.000000 * 1234.000000 = 1522756.000000
Explanation:
  1. The 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 choice of 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
    • 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