# Displaying Maximum and Minimum Value For Linear Search

I decided to work on CodeAbbey exercises for some practice in C++. I'm currently working on Problem #15 (Maximum or Array), which tells me to: create a linear search on an array(of size 300), find the maximum and minimum values in the list, then print out the max and min.

It seems that I got everything BUT displaying the min, and I was wondering if you guys were able to point me in the right direction.

Here is my code so far:

``````#include <iostream>
using std::cout;
using std::cin;

int main() {
int arrayLength[300];

cout << "Please enter the numbers you would like to perform a linear search in: \n";
for(int i=0; i<=300; i++) {
cin >> arrayLength[i];
}

//Store the current maximum in a separate variable
int max=arrayLength[0];
int min=arrayLength[0];

for(int i=0; i<=300; i++) {
if(arrayLength[i] > max) {
max = arrayLength[i];
} else if(arrayLength[i] < min) {
min = arrayLength[i];
}
}

cout << "\n" << max;
cout << "\n" << min;

return 0;
}
``````

Now when I run it, the code executes and prints the maximum number but not the min. How can I fix this?

The line `for(int i=0; i<=300; i++)` looks to be incorrect. Your array `int arrayLength[300]` contains 300 ints. If you count from 1 to 300 there are 300 numbers, but your loop counts from 0 to 300, which is 301 numbers.

The highest index into an array of length `n` is actually `n-1` because the first array index is 0.

``````int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4; // arr holds 3 ints not 4!
``````

Also, the code printing the values might not be exactly what you expect either.

``````cout << "\n" << max;
cout << "\n" << min;
``````

If we draw `\n` to show where your new lines are we get

``````\n
MAX\n
MINotherstuffblahblah
``````

``````cout << max << "\n";
cout << min << "\n";
``````

Results in

``````MAX\n
MIN\n
otherstuffblahblah
``````

making it easier to see your minimum value.

Change both of the `<=` to `<`. The array indices of an array of size 300 run from 0 to 299. When I ran it, the min was right, but the max was wrong. When you index out of bounds, results are not predictable. "Undefined behavior" it's called.