In: Computer Science
2) Write an elementary calculator in which the main program reads an integer input, an operation (+,-,*,/), and another integer input. It then passes this information to a function (calc) to perform this operation. This function (calc) returns the result using switch statements for operation decision. The program stops when the user inputs 0 for both integer inputs in the main program.
#include<stdio.h>
int main()
{
int first,second,operator,ans;
while(1)
{
printf("1.+\n2.-\n3.*\n4./\n");//this is line is written to display
the available operation in the program.
printf("Enter first
number:");
scanf("%d",&first);
printf("Enter second
number:");
scanf("%d",&second);
//this condition is for terminate the loop if user enters to
inputs 0
if(first==0 &&
second==0)
{
break;
}
printf("Enter select the
operation:");
scanf("%d",&operator);
ans=cal(first,second,operator);
printf("%d\n\n",ans);
}
}
int cal(int a,int b,int c)
{
switch(c)
{
case 1:
return
a+b;
break;
case 2:
return
a-b;
break;
case 3:
return
a*b;
break;
case 4:
return
a/b;
break;
}
}
NOTE:
This only worked for integers.