Question: Using the code fragment below, fill in the missing sections with the comments as a guide XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #include #include // The four arithmetic operations ...
Using the code fragment below, fill in the missing sections with the comments as a guide
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#include
#include
// The four arithmetic operations ... one of these functions is selected
// at runtime with a switch or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement
//
void Switch(float a, float b, char opCode) {
float result;
// execute operation
switch(opCode) {
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
printf("Switch: 2+5=%.2lf ", result); // display result
}
// Solution with a function pointer
//
// takes two floats and returns a float
// 4. fill in the parameters, 3 of them, the 3rd
// one should be the function pointer
void Replace_Switch( ) {
float result;
// 5. call the function using the function pointer
// sent in as the third argument
result =
printf("Switch replaced by function pointer: 2+5=");
printf("%.2lf ", result);
}
int main() {
float result;
// 1. declare a function pointer and assign it
// to point to the plus function
// 2. call function with function pointer assigning result to
// the function call and sending 2 and 5 as the arguments
printf("%.2lf ", result);
// the function using switch and no function pointer
Switch(2,5, '+');
// 3. call function using the function that replaces switch
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
