### Arrays: Getting the average of values

Hi there, i need to write a program (not using functions) to read in a sequence of up to ten numbers terminated with the sentinel value -1 from the keyboard and to store them in an integer array. Note that the -1 value shouldn't be stored in the array. the number of non sentinel values read in should be kept in a separate variable. After the user enters the numbers, the program should display how many numbers were entered, the average of those values, number of values below the average, as well as the values in reverse order.

so far i am able to read in numbers and terminate the loop after -1 is entered at which point the program displays how many numbers were entered but the average that it displays is wrong.. any help is greatly appreciated!

 ``1234567891011121314151617181920212223242526272829303132333435363738`` `````` #include using namespace std; int main() { // Variables const int size = 10; int Array[size]; int numbers; int i = 0; double average; double total = 0; // Getting input cout << "Enter a number or -1 to quit: "; cin >> numbers; while (numbers != -1 && i < size) { i ++; Array[i - 1] = numbers; cout << "Enter a number or -1 to quit: "; cin >> numbers; } cout << endl; cout << i << " numbers were read in." << endl; for (i = 0; i < size; i++) total = total + Array[i]; average = total/ Array[i]; cout << "The average is: " << average << endl; system ("pause"); return 0; }``````

 ``` Enter a number or -1 to quit: 4 Enter a number or -1 to quit: 2 Enter a number or -1 to quit: 6 Enter a number or -1 to quit: -1 3 numbers were read in. The average is: 7 ```
On line 30 you set i to 0, losing the actual amount of numbers read in.

So, regardless of the amount of numbers you entered, you process size numbers in the for loop that begins on line 30.

On line 32, the average should be total / number_of_numbers. Array[i] is a nonexistent element.
so in my for loop what should i make 'i' equal to in order to keep track of the amount of numbers read in?
 ``12345678910111213`` ``````// Getting input const int sentinel = -1; int i = 0; do { cout << "Enter a number or " << sentinel << " to quit: "; int number = sentinel; if ( cin >> number && number != sentinel ); { Array[i++] = number; } } while ( i < size && number != sentinel );``````

Last edited on
Topic archived. No new replies allowed.