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...?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<iostream>
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.
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).
Last edited on
Thank you :)
Topic archived. No new replies allowed.