Array of Function Pointer Exercises.
Question
Array of Function Pointer Exercises. (Calculating Circle Circumference, Circle Area or Sphere Volume Using Function Pointers) .Using the techniques you learned in create a text-based. a menu-driven program that allows the user to choose whether to calculate the circumference of a circle. the area of a circle or the volume of a sphere. The program should then input a radius from the user, perform the appropriate calculation and display the result. Use an array of function pointers in which each pointer represents a function. that returns void and receives a double parameter. The corresponding functions should each display messages indicating which calculation was performed., the value of the radius, and the result of the calculation.
Explanation
In C++ pointer is something that refers to points something in a program. Something like a function.
Syntax: return_type *function_pointer(parameter)=&function_name.
In the above question, we use an array of function pointers to perform the given operation.
Pseudo Code:
Here we create a function. Called as pointer array with return type as void and a double as a parameter for radius. And then we Initialize it with three functions. Functions for calculation of circumference, area, and volume. After that, we define a function with the three names that we defined earlier. Next user will enter the radius for the circle. With that radius, three options will be displayed. To which user can choose if he wants circumference, area, or volume. These three given numbers as 0,1, and 2. The user will enter the number for what he wants. In the end result will be displayed on the basis of what the user entered. by using function (*function_pointer[index])(parameter).
Code
#include<conio.h> #include<stdio.h> //function prototypes void circumference(double r); void area(double r); void volume(double r); //main function void main() { //fp is a function pointer array //all the three functions are assigned to the pointer array void (*fp[3])(double)={circumference,area,volume}; int n; double radius; //input radius from user printf("\nEnter radius of the circle: "); scanf("%lf",&radius); printf("0.Circumference"); printf("\n1.Area"); printf("\n2.Volume"); printf("\nEnter you choice: "); scanf("%d",&n); //input user choice //function call if(n>2) printf("\nWrong choice"); else (*fp[n])(radius); } //function to calculate circumference void circumference(double r) { printf("\nCircumference of the circle of radius %lf is %lf",r,2*3.14*r); } //function to calculate area void area(double r) { printf("\nArea of the circle of radius %lf is %lf",r,3.14*r*r); } //function to calculate volume void volume(double r) { printf("\nVolume of the circle of radius %lf is %lf",r,4.18*r*r*r); }
Output