Min and Max Value in Array

I am trying to find the minimum and maximum value from my text file array but the output is always 0 for both the max and min.

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
#include <iostream>
#include <fstraem>

using namespace std; 

//variables
int length;
int exam[1000];

int findMax(int exam[], int length) {
    int maxScore=exam[0];
    for(int i=1; i>length; i++) {
        if(exam[i]>maxScore) {
            maxScore=exam[i];
        }
    }
    return maxScore; 
}

int findMin(int exam[], int length) {
    int minScore=exam[0];
    for(int i=1; i<length; i++) {
        if(exam[i]<minScore) {
            minScore=exam[i];
        }
    }
    return minScore;
}

int main() {
    cout<<"--------------------"<<endl;
    cout<<"Exam Statistics Program"<<endl;
    ifstream f;
    f.open("exam.txt");
    f>>length;
    cout<<"Maximum Score: "<<findMax(exam, length)<<endl;
    cout<<"Miniimum Score: "<<findMin(exam, length)<<endl;
    f.close();
    return 0;
}
Last edited on
The only thing you ever read from exam.txt is the length. You must also read all the values from the file into your exam[] array.

Also, if you're going to pass the array and exam[] length as the parameters to your functions, you may define those variables inside main instead of globally.

I imagine your debugger is playing nicely and zeroing out the memory for you. In other words, exam[] is full of zeroes without you explicitly doing it. So findMax and findMin are operating on an array full of zeroes.
Last edited on
I imagine your debugger is playing nicely and zeroing out the memory for you.

The length and exam are global variables. They have a bit different initialization rules than local variables -- they are zero-initialized?
https://en.cppreference.com/w/cpp/language/initialization
This program can be simplified.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <limits>

int main() {
    std::ifstream f("exam.txt");

    if (!f)
        return (std::cout << "Cannot open file\n"), 1;

    int nomin {std::numeric_limits<int>::max()}, nomax {std::numeric_limits<int>::min()};

    for (int n {}; f >> n; ) {
        if (n > nomax)
            nomax = n;

        if (n < nomin)
            nomin = n;
    }

    std::cout << "Maximum Score: " << nomax << '\n';
    std::cout << "Minimum Score: " << nomin << '\n';
}


You don't provide a sample data file so this was used:


10 20 30 35 15 5 56 87 98 76


giving:


Maximum Score: 98
Minimum Score: 5

Topic archived. No new replies allowed.