The cout statements in the first for loop are printing out strange values.Code:#include <iostream> using namespace std; int *allocate (int number); float average(int *array, int number); void sort (int *array, int number); int main() { int number; int *p; cout << "How many test score do you want to average?" << endl; cin >> number; while (allocate(number) == NULL) { cin.clear(); cin.ignore(); cout << "There was an error in allocating elements" << endl; cout << "Please try again." << endl; cin >> number; } p = allocate(number); cout << "\nEnter the test scores" << endl; for (int i = 0; i < number; i++) { cout << "Test score" << " #" << *(p + i + 1); cin >> *(p + i); if (cin.fail() || *(p + i) < 0) { cout << "Invalid entry" << endl; cout << "Re-enter" << endl; cout << "Test score" << " # " << *(p + i + 1); cin >> *(p + i); } } sort(p, number); cout << "\nHere are the scores you entered in sorted form:" << endl; for (i = 0; i < number; i++) cout << *(p + i) << endl; cout << "\nThe average of the scores is " << average(p, number) << endl; return 0; } int *allocate(int number) { int *array; array = new int[number]; return array; delete [] array; } float average(int *array, int number) { float sum = 0.0f; for (int i = 0; i < number; i++) { sum += *array++; } return sum / number; } void sort (int *array, int number) { int hold; int finish; do { finish = 0; for (int i = 0; i < number - 1; i++) { if (*(array + i) > *(array + i + 1)) { hold = *(array + i); *(array + i) = *(array + i + 1); *(array + i + 1) = hold; int finish = 1; } } }while (finish != 0); }
I'm not sure what's wrong with this:
Also, did I put delete [] array; in the right place?Code:cout << "Test score" << " #" << *(p + i + 1);



LinkBack URL
About LinkBacks




CornedBee
.