Write a C program to Create an array of (void * -type) pointers of length 5. Each of these pointers should be pointing to individual functions that perform operations like addition, subtraction, division, multiplication, exponentiation.
add(){ sub(){ mul(){ div(){ exp(){
} } } } }
These functions could take arguments just like regular functions.
#include <stdio.h>
#include <math.h>
void add(int a, int b) {
printf("%d + %d = %d\n",a,b,(a+b));
}
void sub(int a, int b) {
printf("%d - %d = %d\n",a,b,(a-b));
}
void div(int a, int b) {
printf("%d / %d = %.2f\n",a,b,((float)a/(float)b));
}
void mul(int a, int b) {
printf("%d * %d = %d\n",a,b,(a*b));
}
void exp(int a, int b) {
printf("%d ^ %d = %.2f\n",a,b,pow((float)a,(float)b));
}
int main() {
int i;
int number1;
int number2;
typedef void (*type)(int, int);
type functions[] = {&add, &sub, &div, &mul, &exp};
printf("Enter number 1: ");
scanf("%d",&number1);
printf("Enter number 2: ");
scanf("%d",&number2);
for (i = 0; i < 5; ++i){
functions[i](number1, number2);
}
getchar();
getchar();
return 0;
}
Comments
Leave a comment