C++ Problem: Grading a Multiple-Choice Test

The problem is to write a program that will grade multiple-choice tests.

Suppose there are 8 students and 10 questions, and the answers are stored in a two-dimensional array. Each row records a student’s answers to the questions. For example, the following array stores the test.

The key is stored in a one-dimensional array, as follows:

Your program grades the test and displays the result. The program compares each student’s answers with the key, counts the number of correct answers, and displays it. Listing 8.2 gives the program.

Listing 8.2 GradeExam.cpp

1 #include <iostream>
2
using namespace std;
3
4
int main()
5 {
6   
const int NUMBER_OF_STUDENTS = 8;
7   
const int NUMBER_OF_QUESTIONS = 10;
8
9   
// Students’ answers to the questions
10   char answers[NUMBER_OF_STUDENTS][NUMBER_OF_QUESTIONS] =
11   {
12      {
‘A’, ‘B’, ‘A’, ‘C’, ‘C’, ‘D’, ‘E’, ‘E’, ‘A’, ‘D’},
13      {
‘D’, ‘B’, ‘A’, ‘B’, ‘C’, ‘A’, ‘E’, ‘E’, ‘A’, ‘D’},
14      {
‘E’, ‘D’, ‘D’, ‘A’, ‘C’, ‘B’, ‘E’, ‘E’, ‘A’, ‘D’},
15      {
‘C’, ‘B’, ‘A’, ‘E’, ‘D’, ‘C’, ‘E’, ‘E’, ‘A’, ‘D’},
16      {
‘A’, ‘B’, ‘D’, ‘C’, ‘C’, ‘D’, ‘E’, ‘E’, ‘A’, ‘D’},
17      {
‘B’, ‘B’, ‘E’, ‘C’, ‘C’, ‘D’, ‘E’, ‘E’, ‘A’, ‘D’},
18      {
‘B’, ‘B’, ‘A’, ‘C’, ‘C’, ‘D’, ‘E’, ‘E’, ‘A’, ‘D’},
19      {
‘E’, ‘B’, ‘E’, ‘C’, ‘C’, ‘D’, ‘E’, ‘E’, ‘A’, ‘D’}
20   };
21
22   
// Key to the questions
23    char keys[] = {‘D’, ‘B’, ‘D’, ‘C’, ‘C’, ‘D’, ‘A’, ‘E’, ‘A’, ‘D’};
24
25   
// Grade all answers
26    for (int i = 0; i < NUMBER_OF_STUDENTS; i++)
27    {
28       
// Grade one student
29        int correctCount = 0;
30       
for (int j = 0; j < NUMBER_OF_QUESTIONS; j++)
31        {
32           
if (answers[i][j] == keys[j])
33            correctCount++;
34        }
35
36        cout <<
“Student ” << i << “‘s correct count is ” <<
37        correctCount << endl;
38    }
39
40   
return 0;
41 }

The statement in lines 10-20 declares and initializes a two-dimensional array of characters. The statement in line 23 declares and initializes an array of char values.

Each row in the array answers stores a student’s answer, which is graded by comparing it with the key in the array keys. Immediately after a student is graded, the result for the student is displayed.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *