Linear Search using Arrays

The purpose of this program is to read in string of student answers from a test, and compare those to a string key from an input file. The problem encountered is trying to find the highest score of the student answers using a linear search (see getHigh function)

//prototypes
int getGrade(ifstream&, string, string);
int get_numStud_score(int [])
int getHigh (int []);
int getLow (int []);
void getMean ();

const int questions = 10;

int main()
{


int numScores = 11;
int test_scores[questions];
string student_answers;
string key;
int numrightAns;




ifstream inFile;
inFile.open ("grade_data.txt");

if (!inFile)
{
cout << "Error: File failed to open" << endl;
}

inFile >> key;

int counter = 1;

while(inFile >> student_answers)
{
cout << "Student " << counter << " - ";
int numrightAns = getGrade(inFile,student_answers,key);
cout << numrightAns << endl;
counter ++;
}

int highest = getHigh(test_scores);
cout << "The highest score is: " << test_scores[highest] << endl;

int lowest = getLow(test_scores);
cout << "The lowest score is: " << test_scores[lowest] << endl;



return 0;
}

int getGrade(ifstream &inFile,string student_answers,string key)//How many answers each student got correct
{

int numrightAns = 0;

for ( int i = 0; i < questions ; i++ )
{
if( key[i] == student_answers[i] )
{
numrightAns++;

}
}

return numrightAns;
}


int getHigh(int test_scores[])
{

int highest = 0;

for ( int i = 1; i < questions; i ++)
{
if (test_scores[i] < test_scores[highest])
{
highest = i;
}
}

return highest;
}

int getLow (int test_scores[])
{
int lowest = 0;

for (int i = 1; i < questions; i++)
{
if (test_scores[i] < test_scores[lowest])
{
lowest = i;

}
}
return lowest;
}
You haven't initialized the test_scores array. Additionally, why did you initialize the i in the for loop in the getHigh() function to 1? Lastly, in the following:
1
2
3
if(test_scores[i] < test_scores[highest]) {
highest = i;
}

you are swapping highest with i if the element at i is less than the element at highest; is that what you want to do?
Last edited on
Topic archived. No new replies allowed.