// this program asks the user to enter integer values // into an array, sorts the array, and prints out // the sorted array and the average of all values in // the array. // // This is almost identical to bubblesort2.cpp, except // that it uses a slightly different version of the // print_int_array function. #include #include // sorts the array n in ascending order of its elements. // length is the number of elements in the array n. void bubblesort(int * n, int length) { int number_of_passes = 0; while(1) { number_of_passes++; int changes_made = 0; int i; for (i = 0; i < length-1; i++) { if (n[i] > n[i+1]) { int temporary = n[i]; n[i] = n[i+1]; n[i+1] = temporary; changes_made = 1; } } if (changes_made == 0) { break; } } printf("%d passes were made\n", number_of_passes); } // prints the elements of the array n. See bubblesort1 // for an alternative version of this function. // length is the number of elements in the array n. void print_int_array(int * a, int length) { int i; for (i = 0; i < length; i++) { printf("a[%d] = %d\n", i, a[i]); } } // computes the average value of all elements in the array n. // length is the number of elements in the array n. double array_mean(int * a, int length) { int i; int sum = 0; for (i = 0; i < length; i++) { sum = sum + a[i]; } double sum2 = (double) sum; double length2 = (double) length; return sum2 / length2; } int main() { int length; printf("how many numbers do you want to enter?\n"); scanf("%d", &length); // create an array of ints. The number of elements // in the array is specified by the value of length // (which was specified by the user) int * numbers = (int *) malloc(sizeof(int) * length); // ask the user to enter a value for each element in the array. int i; for (i = 0; i < length; i++) { printf("please enter a value for element %d:\n", i); scanf("%d", &numbers[i]); } // print the array before sorting. printf("\nbefore sorting:\n"); print_int_array(numbers, length); // sort the array bubblesort(numbers, length); // print the array after sorting printf("\nafter sorting:\n"); print_int_array(numbers, length); // compute and print the average value in the array. double mean = array_mean(numbers, length); printf("the average value is %lf\n", mean); // for every array that we create with malloc, we must // destroy with free, when we don't need the array anymore. free(numbers); }