/* Jay Converse */ /* CS 367 Spring 2009 */ /* Homework 2 */ #define MAXINPUT 20 #include #include int main(); int promptNumber(); void readNumbers(int *arraypointer, int numbernums); void maxMin(int *arraypointer, int numbernums, int *largest, int *smallest); int main () { /* Initializing array*/ int array[MAXINPUT]; /* Initializing the pointer to the array */ int *arraypoint = array; /* Rest of vars init */ int input; int numOfNums; float average; int largest = 0; int smallest; int *largestp = &largest; int *smallestp = &smallest; /* Call promptNumber to get the number of numbers to be entered */ numOfNums = promptNumber(); /* Use that number to read into the array and pass the pointer */ readNumbers(arraypoint, numOfNums); /* Recenter the array pointer */ arraypoint = array; /* Find the max and min of the array numbers */ maxMin(arraypoint, numOfNums, largestp, smallestp); /* Print result*/ average = (largest + smallest)/2; printf("The largest number is %d ",largest); printf("and the smallest number is %d.\n",smallest); printf("The average of these two is %5.2f.\n",average); /* Pause to allow user to read */ system("pause"); return 0; } void maxMin(int *arraypointer, int numbernums, int *largest, int *smallest) { /* temp variables store integers for easier use in calculations */ int temp; temp = *arraypointer; /* this algorithm is the same as for homework 1 except using pointers. the "smallest" starts as the first in the array and the largest is 0. each pass, it's checked for whether the current number is greater than largest or smaller than smallest, and the numbers are changed if that's the case. */ *smallest = temp; *largest = 0; int j; j=0; for (j = 0; j < numbernums; j++) { temp = *arraypointer; int temp2; temp2 = *smallest; if (temp < temp2) { temp = *arraypointer; *smallest = temp; } temp2 = *largest; if (temp > temp2) { temp = *arraypointer; *largest = temp; } arraypointer = arraypointer + 1; } } int promptNumber() { /* Asks user for number of numbers to enter, and returns that to main.*/ int number; printf("Please enter number of numbers.\n"); scanf("%d",&number); return number; } void readNumbers(int *arraypointer, int numbernums) { /* j is used for loop, and input is used for temporary storage of the int. Again, probably not the best way to do it, but it's the way I do it out of habit. */ int j; int input; printf("Enter the numbers. (Press after each number.)\n"); for (j = 0; j < numbernums; j++) { scanf("%d",&input); *arraypointer = input; arraypointer = arraypointer + 1; } }