How do i find the max and min from a file using array and a loop?

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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
//initialize my variables
    int Sum = 0;
    int Average = 0;
    int salesV[12]= {};
    ifstream Numbers;   //object accosiated with file
    int index =0;


Numbers.open("salesUnit.dat");//object associated with my file
    if (!Numbers.is_open()){
    cerr<<"Sorry file could not be opened";}  /error if file is not open

    else {
             //loop to read all the numbers in the file
        while (!Numbers.eof()){

                      Numbers >>salesV[index];
                  Sum=Sum+salesV[index];//finding the sum of the numbers
                          ++index;
                                 }


                          while (!Numbers.eof()){

                      Numbers >>salesV[index];
                      Sum=Sum+salesV[index];
                          ++index;
                                 }



Average = Sum/12;  //the average of the numbers


[output] cout<<"The average of the numbers is:"<<Average<<endl;// display the average 
 cout<<"The Sum of the numbers is:"<<Sum;   //display the sum
[/output]
    }


    return 0;
}
Last edited on
These are the numbers in the file " salesUnit.dat " saved using notepad

204
156
132
111
350
98
88
59
211
142
332
141
You could try a for loop with 2 if conditionals in it. Declare 2 ints, Min and Max, and initialize them to the first element of the array just before the for loop. Then have the for loop iterate through the array (ie, with something like for (int i = 0; i < index; i++). Then the 2 ifs could be something like

1
2
3
4
if (salesV[i] < Min)
    Min = salesV[i];
else if (salesV[i] > Max)
    Max = salesV[i];
I don't like the idea of this: Average = Sum/12;
What if the file contains more or less than 12 items? Better to use the count of how many items were actually read, I think.

Find the minimum. You could do max in a similar way, in the same loop.
1
2
3
4
5
6
7
    int min = salesV[0];

    for (int i=1; i<count; i++)
    {
        if (salesV[i] < min)
            min = salesV[i];
    }
Last edited on
As to get accurate result u must use float average;
instead of int average ;
Thank you so much for your help i will also help others with this problem. Thanks again :)
Topic archived. No new replies allowed.