I am to make a program that uses function pointers to give an output of adding numbers together or taking the average of these three numbers. I have almost most of it figured out, but am running into a problem. I am supposed to print out also which option they choose, but when I put a print statement into the function, it prints that statement out twice. I'm assuming because the first time it goes to that function and prints it out, then when I call that function in the print statement in main, it prints it out again. I'm not sure. Any advice would be appreciated. Thank you.
Code:
#include <stdio.h>
int addFunct(int num1, int num2, int num3);
int averageFunct(int num1, int num2, int num3);
int main()
{
int num1 , num2, num3, option;
int (*f[2])(int num1, int num2, int num3) = {addFunct, averageFunct};
printf("Please enter a number greater than 0 to start.\nEnter a negative number to quit.\n");
printf("Please enter the first number.\n");
while (num1 >= 0)
{
scanf("%d", &num1);
printf("Please enter the second number.\n");
scanf("%d", &num2);
printf("Please enter the third number.\n");
scanf("%d", &num3);
printf("What would you like to do? Please pick the appropriate number.\n");
scanf("%d", &option);
if (option >= 0 && option < 2)
(*f[option])(num1, num2, num3);
printf("The answer is %d", f[option](num1, num2, num3));
printf("Please enter the first number.\n");
scanf("%d", &num1);
}
return 0;
}
int addFunct(int num1, int num2, int num3)
{
int add = 0;
printf("You have chosen to add the two numbers.\n" );
add = num1 + num2 + num3;
return add;
}
int averageFunct(int num1, int num2, int num3)
{
int average = 0;
printf("You have chosen to average the three numbers.\n");
average = (num1 + num2 + num3) / 3;
return average;
}