2. Write an elementary calculator in which the main program reads two integer in
ID: 3729685 • Letter: 2
Question
2. Write an elementary calculator in which the main program reads two integer inputs and the operation(+,-,*,/) between them and passes that information to a function (calc) to perform this operation. This function returns the result using switch statements for operation decision. The program stops when the user inputs 0 for both inputs in the main program.
This is meant to be done in C programming. I will be testing the result on the Rasp Pi3, please be accurate. I'll upvote if helpful. Thanks!
Explanation / Answer
#include<stdio.h>
/***
calc function which uses three parameters and perform the specific operation depending upon the operation type
***/
float calc(int first, int second, char ch){
float result = 0;
switch(ch){
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = (float)first/ (float)second;
break;
default :
break;
}
return result;
}
/****
The main function reads three argument integer input 1 , integer input 2 and operation
if operation is other than +,-,*,/ is not supported .
if both the inputs are 0 then programs exit by giving the message
if operation is / and second input is 0 then as it is divide by 0 so program exits by giving message
****/
int main(){
int firstOperand;
int secondOperand;
char op;
printf("Please enter first integer input ");
scanf("%d",&firstOperand);
printf("Please enter second integer input ");
scanf("%d",&secondOperand);
printf("Please enter the operation you want to perform: +,-,*,/: ");
scanf(" %c", &op);
if(firstOperand == 0 && secondOperand == 0){
printf("Both the input integers are 0 . So exiting ");
}
if(op == '+' || op == '-' || op == '*' || op == '/'){
if(op == '/' && secondOperand ==0){
printf("Division by 0 is not allowed");
return 0;
}
float result = calc(firstOperand, secondOperand, op);
printf("The result is : %f", result);
}else{
printf("Invalid operation. So exiting ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.