LearnFrenzy
Sign in Take a free test

Classes and Objects · Class Programs · Question 4

Student report card with an array of objects in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Read n students with three marks each into a vector of Student objects; each object computes its total, percentage and result. Print a report and the topper.

Solution
main.cpp
#include <format>
#include <iostream>
#include <string>
#include <vector>

class Student {
    std::string name_;
    int marks_[3]{};
public:
    friend std::istream& operator>>(std::istream& in, Student& s) {
        return in >> s.name_ >> s.marks_[0] >> s.marks_[1] >> s.marks_[2];
    }
    int total() const { return marks_[0] + marks_[1] + marks_[2]; }
    double percent() const { return total() / 3.0; }
    bool passed() const { for (int m : marks_) if (m < 35) return false; return true; }
    const std::string& name() const { return name_; }
};

int main() {
    int n;
    std::cin >> n;
    std::vector<Student> cls(n);
    for (auto& s : cls) std::cin >> s;
    const Student* top = &cls[0];
    for (const auto& s : cls) {
        std::cout << std::format("{:<6}{:>4}{:>7.1f}%  {}\n", s.name(), s.total(), s.percent(), s.passed() ? "PASS" : "FAIL");
        if (s.total() > top->total()) top = &s;
    }
    std::cout << "Topper: " << top->name() << '\n';
    return 0;
}

Output Verified by compiling and running

Asha   259   86.3%  PASS
Ravi   135   45.0%  PASS
Meera  275   91.7%  PASS
Kabir   99   33.0%  FAIL
Topper: Meera

An overloaded operator>> lets each Student read itself. Kabir fails because two subjects are below 35, even though the rule is checked per subject, not on the average.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links