1. Engineering
  2. Computer Science
  3. using the code fragment below fill in the missing sections...

Question: using the code fragment below fill in the missing sections...

Question details

Using the code fragment below, fill in the missing sections with the comments as a guide

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#include <stdio.h>

#include <stdlib.h>

// 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

// <opCode> specifies which operation to execute

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\n", result);         // display result

}

// Solution with a function pointer

// <pt2Func> is a function pointer and points to a function that

// 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\n", 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\n", result);

// the function using switch and no function pointer

Switch(2,5, '+');

// 3. call function using the function that replaces switch

return 0;

}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution