Determine class average based on 10 grades entered by user in class member function - C++ Class

C++ examples for Class:Member Function

Description

Determine class average based on 10 grades entered by user in class member function

Demo Code

                   
#include <string>
#include <iomanip>
#include <iostream>
                   /*w ww . j a  v a  2  s.c o m*/
class Course {
 private:
    std::string courseName;
                   
 public:
    Course(std::string);
                   
    // SETTERS
    void setCourseName(std::string);
                   
    // GETTERS
    std::string getCourseName();
                   
    void displayMessage();
    void determineClassAverage();
};
                   
Course::Course(std::string name) { setCourseName(name); }
// SETTERS
void Course::setCourseName(std::string name) {
    if (name.length() <= 25)
        courseName = name;
    else {
        courseName = name.substr(0, 25);
        std::cout << "Name \"" << name << "\" exceeds maximum length (25).\n";
        std::cout << "Limiting courseName to first 25 characters.\n" << std::endl;
    }
}
// GETTERS
std::string Course::getCourseName() { return courseName; }
// display a welcome message to the Course user
void Course::displayMessage() {
    std::cout << getCourseName() << "!\n" << std::endl;
}
// 
void Course::determineClassAverage() {
    int total;
    int gradeCounter;
    int grade;
    double average;
                   
    total = 0;
    gradeCounter = 0;
                   
    std::cout << "Enter grade or -1 to quit: ";
    std::cin >> grade;
                   
    while (grade != -1) {
        total += grade;
        gradeCounter++;
                   
        std::cout << "Enter grade or -1 to quit: ";
        std::cin >> grade;
    }
                   
    if (gradeCounter != 0) {
        // calculate the average of all entered grades
        average = static_cast<double>(total) / gradeCounter;
                   
        std::cout << "\nTotal of all " << gradeCounter << " grades is " << total << std::endl;
        std::cout << "Class average is " << std::setprecision(2) << std::fixed << average << std::endl;
    } else
        std::cout << "No grades were entered" << std::endl;
}
                   
int main(int argc, const char *argv[]) {
    Course myCourse("C++");
                   
    myCourse.displayMessage();
    myCourse.determineClassAverage();
    return 0;
}

Result


Related Tutorials