You are using a version without Ads of this website. Please, consider donating:

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

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````#include #include 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:"<
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

 ``1234`` ``````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.
 ``1234567`` `````` int min = salesV[0]; for (int i=1; 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.