lowest value in an array (pointing out error.)

I am having a problem with getting the lowest value in an array, although everything else is working fine (even getting the highest value in an array.) What is causing my error? I thought it was maybe the highest value that's messing with the numbers so I comment it out, although I'm still not able to get the right lowest value. I am getting a large negative number.

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
  #include <iostream>
#include <string>
using namespace std;
 
const int SIZE = 5;
 
int main ()
{
   
    string names[SIZE] = {"mild", "medium", "sweet", "hot", "zesty"};
    int sales[SIZE];
    int sum = 0;
    int highest;
    int lowest;
    highest = sales[SIZE];
    lowest = sales[SIZE];
 
    cout << "Enter the number of jars sold for each type of salsa." << endl;
    cout << "mild sold: " << endl;
    cin >> sales[0];
 
    cout << "medium sold: " << endl;
    cin >> sales[1];
 
    cout << "sweet sold: " << endl;
    cin >> sales[2];
 
    cout << "hot sold: " << endl;
    cin >> sales[3];
 
    cout << "zesty sold: " << endl;
    cin >> sales[4];
   
 
    for (int i = 0; i < SIZE; i++)
    {
        if (sales[i] > highest)
            highest = sales[i];
        if (sales[i] < lowest)
            lowest = sales[i];
   
        cout << "Number of jars of " << names[i] << " salsa sold: " << sales[i] << endl;
        sum += sales[i];
    }
   
 
    cout << "The total of jars sold: " << sum << endl;
    cout << "Highest " << highest << endl;
    cout << "Lowest " << lowest << endl;
 
    return 0;
}
The problem is you didn't initialize 'highest' and 'lowest' properly.
Try not initialize your 'highest' and 'lowest' at line 15.
Add the following lines before line 35 (before the for loop)

highest = sales[0];
lowest = sales[0];
1
2
highest = sales[SIZE];
lowest = sales[SIZE];

Note that array indices start from zero so the last element in the array is sales[SIZE - 1].
sales[SIZE] is not a valid element.
Topic archived. No new replies allowed.