/******** This program reads a series of random numbers from a file and calculates and prints the mean and variance of the numbers. The program uses three functions. The first one prompts the user for a file name and then reads the numbers from the file. It expects the first number in the file to be the number of data in the file. It checks for errors and returns to the main program if there was a problem. Note the use of pointers for arguments to this function. The second function calculates, prints and returns the average of the numbers. The third calculates, prints and returns the variance of the numbers. Written by Erik Cheever, 1/94 Update by Bruce maxwell, 1/00 ********/ #include #define MaxNum 1000 // Number of random numbers that can be handled #define ERROR -1 // Constants used to signify errors #define NO_ERROR 0 /* This program reads a file of numbers and returns them in an array. */ int ReadFile(int *nums, int *maxNums) { char FileName[80]; // Note that since maxNum is passed as a pointer we need to use FILE *InFile; // the "*" operator to access the actual value of the variable. int i; /* Get name of file */ printf("Enter file name: "); scanf("%s",FileName); /* Open the file */ InFile = fopen(FileName,"r"); if (InFile == NULL) { /*If error, return and report*/ printf("\nCould not open file '%s'.\n",FileName); return (ERROR); } /* Note since maxNums is a pointer that we don't need to use the "&" operator in the fscanf statement. */ fscanf(InFile,"%d",maxNums); /* Note that since maxNums is a pointer that we need to use the "*" operator when we want to use the value stored where the pointer is pointing. */ if (*maxNums > MaxNum) { //Check if too many to be held in array printf("\nToo much data in file (%d data).\n",maxNums); fclose(InFile); return (ERROR); } /* Read data into array and return */ for (i=0;i<*maxNums;i++) { fscanf(InFile,"%d",&(nums[i])); } fclose(InFile); return(NO_ERROR); } /* This function calculates and prints the average of an array of numbers. It also returns the average value back to the main program. */ float CalcPrintMean(int *nums, int maxNums) { int i; float avg; /* Use a float for the average */ avg = 0.0; for (i=0;i