Accelerated C++ Solution to Exercise 3-5

Exercise 3-5

Write a program that will keep track of grades for several students at once. The program could keep two vectors in sync. The first should hold the student’s names, and the second the final grades that can be computed as input is read. For now, you should assume a fixed number of homework grades. We’ll see in §4.1.3/56 how to handle a variable number of grades intermixed with student names.

Solution

This exercise is a good one. The nature of the problem and the eventual solution builds on all the fundamentals that we have learnt from this chapter. There are many ways to solve this. Here is one of these many ways.

The solution strategy:

  • Create a constant numHomework that defines the fix number of homework scores required for each student.
  • Have an infinite while loop to enable user to enter the studentName – there will be points where the user can exit the program peacefully by entering the end-of-file key (Ctrl-Z / F6 for windows).
  • As soon as a studentName is read, we append it to the studentNames vector – this vector store the studentName elements.
  • Within the while loop we have a for loop to enable user to enter the homeworkScore one by one- until the predefined constant numHomework is reached.
  • During the process we compute the totalScore and subsequently the meanScore for the corresponding student.
  • As soon as the meanScore is computed, we append it to the meanScores vector – this vector store the list of meanScore elements.
  • The nature of the looping systems ensure the two vectors studentNames and meanScores are always in sync.
  • Allow user to either continue (by entering another studentName), or exit (by entering the end-of-file key. i.e. Ctrl-Z or F6 for windows).
  • Output the pairs of studentName and meanScore elements of the vectors studentNames and meanScores using a for loop.

Putting this all together, we have our full program.

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <ios>
#include <string>
#include <vector>

using std::cin;             // <iostream>
using std::cout;            // <iostream>
using std::endl;            // <iostream>
using std::setprecision;    // <iomanip>
using std::sort;            // <algorithm>
using std::streamsize;      // <ios>
using std::string;          // <string>
using std::vector;          // <string>


int main()
{
    typedef vector<double>::size_type vecSize;

    const vecSize numHomework = 5;     // max number of homework per student

    string studentName;
    vector<string> studentNames;

    double homeworkScore;
    double totalScore;
    double meanScore;
    vector<double> meanScores;

    cout << "Enter student name: ";
    while (cin >> studentName)
    {
        studentNames.push_back(studentName);
        cout << "Enter " << numHomework << " homework scores below..." << endl;

        totalScore = 0; // Initialise
        meanScore = 0;  // Initialise

        for (vecSize i = 0; i != numHomework ; ++i)
        {
            cin >> homeworkScore;
            totalScore += homeworkScore;
        }

        meanScore = totalScore / numHomework;
        meanScores.push_back(meanScore);

        cout << "Enter another student name "
                "(or enter F6 key to exit): ";
    }

    vecSize numStudents = studentNames.size();
    cout << endl;
    cout << "Number of students entered: " << numStudents << endl;

    streamsize prec = cout.precision();
    for (vecSize i = 0; i != numStudents ; ++i)
    {
        cout << endl;
        cout << "Student: " << studentNames[i] << endl;
        cout << "Mean Score: " << setprecision(5)
            << meanScores[i] << setprecision(prec) << endl;
    }

    return 0;

}

Result

I now run a test to demonstrate the program output.

Enter student name: Johnny
Enter 5 homework scores below...
40
50
60
70
80
Enter another student name (or enter F6 key to exit): Fred
Enter 5 homework scores below...
99
78
67.5
66.8
100
Enter another student name (or enter F6 key to exit): Joe
Enter 5 homework scores below...
0
0
10
2
0
Enter another student name (or enter F6 key to exit): ^Z

Number of students entered: 3

Student: Johnny
Mean Score: 60

Student: Fred
Mean Score: 82.26

Student: Joe
Mean Score: 2.4

Process returned 0 (0x0)   execution time : 55.152 s

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

6 thoughts on “Accelerated C++ Solution to Exercise 3-5”

  1. Question about the vector size_type used here. Line 20 typedefs vecSize as the size type for double vectors, but line 62 uses an index of type vecSize to access a string vector. What’s the difference between vector::size_type and vector::size_type, if any? Is it sound to interchange between the two? (I wouldn’t know how else to solve the problem otherwise.) Thanks!

    1. Ack, some of the content got lost to some HTML formatting. I meant to ask between the vector<double>::size_type and vector<string>::size_type.

      1. Hello. Great spot and thanks for bringing this up. Now that I look at the code again, the code does “smell funny”. I think you are quite right about the vector<double>::size_type vs vector<string>::size_type. I probably had made a mistake there. Probably purely by luck that the code still work (as there aren’t that many observations). I guess this code needs to be corrected :)

        Net net, it is not sound to interchange between the two. The two size types are different. For small number of observations I guess the effect of interchanging the two is not great. For greater number of observations however, that effect would probably become more significant.

        Newbie mistakes – sorry :)

        1. By the way, to quote codes inline, surround the text with single backticks on each side (left and right).

          To quote a code block, have three backticks at the top and at the bottom of the code block. It’s a WordPress markdown thing. (I need to “hack” this comment section sometime to include markdown syntax instructions :)

        2. Hey Johnny! I gotcha, and what you said about the small number of observations makes sense. Thanks for clearing this up! (Now off to more happy hacking :D)

  2. Thought it was a solid problem. I ended up going with the median method that was presented in the chapter to calculate the score. Also used a vector for finals and midterms.

    The sort function can sort subsets, so you just have to offset during the loop based on the number of homeworks. Code doesn’t prompt for names during the loop after the first, cba to fix text prompts.

    code: https://pastebin.com/Be2qu4u1

Comments are closed.