HackerRank C++ Classes and Objects




Kristen is a contender for valedictorian of her high school. She wants to know how many students (if any) have scored higher than her in the 5 exams given during this semester.

Create a class named Student with the following specifications:

An instance variable named to hold a student's 5 exam scores.
A void input() function that reads scores 5 integers and saves them to scores.
An int calculateTotalScore() function that returns the sum of the student's scores.



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <cassert>
  7. using namespace std;
  8. class Student{
  9. int s[5];
  10. public:
  11. void input()
  12. {
  13. for(int i=0;i<5;i++)
  14. {
  15. cin>>s[i];
  16. }
  17. }
  18. int calculateTotalScore()
  19. {
  20. int sum=0;
  21. for(int i=0;i<5;i++)
  22. {
  23. sum=sum+s[i];
  24. }
  25. return sum;
  26. }
  27. };
  28. int main() {
  29. int n; // number of students
  30. cin >> n;
  31. Student *s = new Student[n]; // an array of n students
  32. for(int i = 0; i < n; i++){
  33. s[i].input();
  34. }
  35. // calculate kristen's score
  36. int kristen_score = s[0].calculateTotalScore();
  37. // determine how many students scored higher than kristen
  38. int count = 0;
  39. for(int i = 1; i < n; i++){
  40. int total = s[i].calculateTotalScore();
  41. if(total > kristen_score){
  42. count++;
  43. }
  44. }
  45. // print result
  46. cout << count;
  47. return 0;
  48. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube