Hey all,
im working with inputting and outputting data from files but im having trouble with my mode function in this code, I get no errors but when I run the program it crashes. I believe it should work but if someone could either one find an error or two has a streamlined way of tackling this issue it would be greatly appricated!
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int Average ( int grades [] )
{
int sum;
for (int j = 0; j < 20 ; j++)
{
sum += grades[j];
}
sum = sum/20;
return sum;
}
int Mode ( int grades [] )
{
int MIRGrades[20];//creates mirror array
for (int q =0; q<20; q++)
{
MIRGrades[q] = grades[q]; //copys grades array into mirror array
}
int FArray[20];//creates frequency array
for (int y =0; y<20; y++)
{
for (int x=0; x<20; x++)
{
if ( MIRGrades[x] == grades[y])
{
FArray[y] ++;// compares one element in original array to all in
} // mirror, every match adds one to frequency array
}
}
int Max = 0;
for (int z =0; z<20; z++)
{
if (FArray[z] > Max) //determines which element had most matches
Max = FArray[z];
}
return Max;// returns element number of most occuring
}
int main(int argc, char *argv[])
{
constint SIZE = 20;
string names[SIZE];
int grades[SIZE];
ifstream GetData;
GetData.open("Grades.txt");
for (int i = 0; i < SIZE; i++)
{
GetData >> names[i];
GetData >> grades[i];
}
cout << Average(grades);
int MODE = Mode(grades);
cout << grades[MODE];
system("PAUSE");
return EXIT_SUCCESS;
}
There are a few problems here. I don't know how many lines there are in the file "Grades.txt". The program assumes there will be at least 20. If there are fewer lines then the elements of the array will not be properly initialised.
I would use a separate variable to count how many lines have been read, like this:
1 2 3
int count = 0;
while ( GetData >> names[count] >> grades[count])
count++;
That reads the data and counts it at the same time.
Then pass the value of count to the other functions.
Function Mode() is supposed to return the array index, but it instead returns a value. There is no need for the mirror array, that is adding extra complication for no benefit.
int Mode ( int grades [], int count )
{
int FArray[SIZE] = { 0 }; // sets frequency array elements to zero
for (int y =0; y<count; y++)
{
for (int x=0; x<count; x++)
{
if ( grades[x] == grades[y])
{
FArray[y] ++; // compares each element in array to all the other elements
} // every match adds one to frequency array
}
}
int Max = 0;
int index = 0;
for (int z =0; z<count; z++)
{
if (FArray[z] > Max) // determines which element had most matches
{
Max = FArray[z];
index = z;
}
}
return index; // returns element number of most occurring
}
Notice that the elements of array FArray[] need to be assigned initial values.