Array Value Assignent Error

In this code I am using a for loop to set the variable min to the minimum value in the array. The same process is working for max, but I don't know why it won't work for min.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
    int bar[10] = {6, 2, 4, 5, 1, 7, 8, 9, 10, 11}, i, max = 0, min = 20;
    for (i = 0; i <= 11; i++)
        if (bar[i] > max)
            max = bar[i];
    if (bar[i] < min)
        min = bar[i];
    cout << max << "  " << min;
    
    return 0;
}
Your 'for' loop only encompasses the first 'if' statement. Use braces. It will make your code clearer anyway.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
    int bar[10] = {6, 2, 4, 5, 1, 7, 8, 9, 10, 11}, i, max = 0, min = 20;
    //per JockX, fix this range so that you only try to access 10 elements, not 12
    for (i = 0; i <= 11; i++)
    {
        if (bar[i] > max)
        {
            max = bar[i];
        }
        if (bar[i] < min)
        {
            min = bar[i];
        }
    }
    cout << max << "  " << min;
    
    return 0;
}
Last edited on
Your loop executes 12 times, but there is only 10 elements in bar. Your program may be crashing or accessing random data at one point. Also, lines 9-10 are outside the for loop, which does not seem like it was intended.
Last edited on
Thanks vey much.
Topic archived. No new replies allowed.