### Arrays

My program stops after it lets the user input a number. Please help. I know it probably has something to do with my arrays...?

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071`` ``````#include using namespace std; void read_array(int n_array[], int& size); int minimum(int n_array[], int size); int maximum(int n_array[], int size); int average(int n_array[], int size); int main(void) { int number_array[19]; int size; cout << " Please enter up to 20 integers. Enter -1 when you are finished." << endl; read_array(number_array, size); minimum(number_array, size); maximum(number_array, size); average(number_array, size); return 0; } void read_array(int n_array[], int& size) { int number; do{ cin >> number; if (number > 0) {n_array[size] = number; size++; } }while (size < 20 && number != -1); } int minimum(int n_array[], int size) { int min = n_array[0]; for (int i = 0; i < size; i++) { if (n_array[i] < min) {min = n_array[i]; } } return min; } int maximum(int n_array[], int size) { int max = 0; for (int i = 0; i < size; i++) { if (n_array[i] > max) {max = n_array[i];} } return max; } int average(int n_array[], int size) { int last = 0; int average; for (int i = 0; i < size; i++) { n_array[i] = last + n_array[i]; last++; average = n_array[i]/size; } return average; }``````

Also, my min, max, and average functions probably need fixing, but I at least want to be able to run the program to see what values they return, so I can modify the code. I would appreciate it if someone could help me get to that point.
Last edited on
That's because you use uninitialized value to access array index.
 ``123456789101112131415161718`` ``````int main(void) { int number_array[19]; int size; // uninitialized, its value is random, probably over 19 :) //... void read_array(int n_array[], int& size) { int number; do{ cin >> number; if (number > 0) {n_array[size] = number; // size is uninitialized, probably over array size - causes crash size++; } }while (size < 20 && number != -1); }``````

Also, your instruction mention that I can input up to 20 integers, but I am only allowed 19 - at 20th run the program crashes even, if the loop executed well 19 times before, as `number_array` has only 19 elements (indexed 0-18).
Last edited on
Thank you :)
Topic archived. No new replies allowed.