#include <iostream>
#include <fstream>
usingnamespace 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;
}
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];
elseif (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];
}