#include<iostream>
usingnamespace 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.
That's because you use uninitialized value to access array index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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).