I want to calculate the average of each student using c++ and multi-dimensional array. In my code below it will display the grade of the each student in each subject. How can I list all the scores and at the end will display the average of each student?

Here is my code:

#include <iostream>

using namespace std;

const int ROWS = 4;
const int COLS = 4;

void fillScores(int[ROWS][COLS]);
void printScores(int[ROWS][COLS]);

int main()
{
    int scores[ROWS][COLS];

    fillScores(scores);
    printScores(scores);

    return 0;
}

void fillScores(int newScores[ROWS][COLS]){
    int score;

    for(int i = 0; i < ROWS; i++){
        cout << "Enter scores for exam " << (i + 1) << ": ";

        for(int j = 0; j < COLS; j++){
            cin >> score;
            newScores[i][j] = score;
        }
    }
}

void printScores(int newScores[ROWS][COLS]){
    for(int i = 0; i < COLS; i++){
        cout << "Student " << (i + 1) << " Scores: ";

        for(int j = 0; j < ROWS; j++){
            cout << newScores[j][i] << " Average Score: " << (newScores[j][i]/COLS);
        }
    }
}

1 Answers

1
Valentino On Best Solutions

If you just want to print it (without storing it in a variable) you can do it when you are printing:

void printScores(int newScores[ROWS][COLS]){
    for(int i = 0; i < COLS; i++){
        cout << "Student " << (i + 1) << " Scores: ";

        float examsum = 0;
        for(int j = 0; j < ROWS; j++) {
            examsum += newScores[j][i];
            cout << newScores[j][i] << " ";
        }

        cout << "Average: " << examsum/ROWS << endl;
    }
}