C++ program to check how many students have greater score than first one

C++Server Side ProgrammingProgramming

Suppose we have n students score on five subjects. The first scores are for Kamal, and there are n-1 more scores for other students and each student has five subjects. We shall have to count number of students who have scored more than Kamal. Here we shall define one class called students to load scores for each students. The class has one Input() function to take input and calculateTotalScore() function to calculate score of a student from given five marks.

So, if the input is like n = 4 scores = [[25,45,32,42,30],[22,25,41,18,21],[37,42,48,45,25],[36,48,35,40,30]], then the output will be 2 because last two students have greater score than Kamal.

To solve this, we will follow these steps −

  • s := an array of Student type object with n elements

  • for initialize i := 0, when i < n, update (increase i by 1), do:

    • load all scores of scores[i] into s[i]

  • kamal_sc := total score of s[0]

  • count := 0

  • for initialize i := 1, when i < n, update (increase i by 1), do:

    • total := total score of s[i]

    • if total > kamal_sc, then:

      • (increase count by 1)

  • return count

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <vector>
using namespace std;
class Student{
   public:
    int score[5];
    void input(vector<int> v){
        for(int i = 0; i < 5; i++)
            score[i] = v[i];
    }
    int calculateTotalScore(){
        int res = 0;
        for(int i = 0; i < 5; i++)
            res += score[i];
        return res;
    }
};
int main(){
    int n = 4;
    vector<vector<int>> scores = {{25,45,32,42,30},{22,25,41,18,21},{37,42,48,45,25},{36,48,35,40,30}};
    Student *s = new Student[n];
    for(int i = 0; i < n; i++){
        s[i].input(scores[i]);
    }
    int kamal_sc = s[0].calculateTotalScore();
    int count = 0;
    for(int i = 1; i < n; i++){
        int total = s[i].calculateTotalScore();
        if(total > kamal_sc){
            count++;
        }
    }
    cout << count;
}

Input

4, {{25,45,32,42,30}, {22,25,41,18,21}, {37,42,48,45,25}, {36,48,35,40,30}}

Output

2
raja
Updated on 07-Oct-2021 07:46:48

Advertisements