2008年12月17日 星期三

Practice of Using an Array of Pointers to Functions

Write a menu-driven interface to process student grades by using an array of pointers to
functions. The student grades are collected as follows:

Student ID Test#1 Test#2 Test#3 Test#4
  1     77   68   86   73
  2     96   87   89   78
  3     70   90   86   81

The program should offer the user four options as follows:

Enter a choice:
0 Print all grades for all students
1 Find the minimum grade of the total 12 grades
2 Find the maximum grade of the total 12 grades
3 Print the average on all tests for each student
4 End program

An individual function should be written for each of the choices from choice 0 through
choice 3, respectively. Store the pointers to the four functions in an array and use the
choice made by the user as the subscript into the array for calling each function. (Note
that: one restriction on using arrays of pointers to functions is that all the pointers must
have the same type. The pointers must be to functions of the same return type that receive
arguments of the same type.)

#include <stdio.h>
#include
<stslib.h>

void print_all(int [][4]);
void find_min(int [][4]);
void find_max(int [][4]);
void print_ave(int [][4]);

int main()
{
 int grade[3][4]={{77,68,86,73},{96,87,89,78},{70,90,86,81}};
 void (*array[4])(int [][4])={print_all,find_min,find_max,print_ave};

 for(;;)
 {
  int request;
  printf("0 Print all grades for all students\n");
  printf("1 Find the minimum grade of the total 12 grades\n");
  printf("2 Find the maximum grade of the total 12 grades\n");
  printf("3 Print the average on all tests for each student\n");
  printf("4 End program\n");
  scanf("%d",&request);
  if(request==4)
   break;
  else if(request>=0&&request<=3)    (*array[request])(grade); // &grade is the same
  else printf("Invalid input.\n");
 }
 system("PAUSE");
 return 0;
}

void print_all(int grade[][4])
{
 printf("\nStudent ID Test#1 Test#2 Test#3 Test#4\n");
 int i,j;
 for(i=0;i<3;i++)
 {
  printf("%4d%13d%7d",i+1,grade[i][0],grade[i][1]);
  printf("%7d%7d\n",
,grade[i][2],grade[i][3]);
 }
 printf("\n");
}

void find_min(int grade[][4])
{
 int i,j,min=101;
 for(i=0;i<3;i++)
  for(j=0;j
<4;j++)
   if(min>grade[i][j])
    min=grade[i][j];
 printf("\nThe minimum of all grades is : %d\n\n",min);
}

void find_max(int grade[][4])
{
 int i,j,max=-1;
 for(i=0;i
<3;i++)
  for(j=0;j
<4;j++)
   if(max
<grade[i][j])
    max=grade[i][j];
printf("\nThe maximum of all grades is : %d\n\n",max);
}

void print_ave(int grade[][4])
{
 printf("\n");
 int i;
 for(i=0;i<3;i++)  {   printf("The average of student ID %d is : ",
,i+1);
  printf("%lf\n",(grade[i][0]+grade[i][1]+grade[i][2]+grade[i][3])/4.0);
 }
 printf("\n");

}

沒有留言: