Commit 8c63e63e by unknown

added homework 2

parent 46596508
8 5
5 4 5 0 2
0 0 0 3 3
2 1 3 4 3
5 4 3 1 2
5 5 5 1 4
4 5 3 5 4
4 4 3 4 5
5 5 5 5 5
\ No newline at end of file
/*
* File: homework2.c
* Author: Tran Minh Huy Vu
*
* Created on October 4, 2018, 1:50 PM
* Description: Creating a 2D array as a score database for students and their grades
* and calculate the average and find the best student.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int grades[15];
float average;
} student;
void getArrayDimension(char*, int);
void getStudentGrades(student*, int, int);
void displayFinalMatrix(student*, int, int);
float getAverage(student, int);
int findBestStudent(student*, int);
int main () {
char arrayDimension[20];
getArrayDimension(arrayDimension, 20);
char* buff = strtok(arrayDimension, " ");
int studentsNo = atoi(buff);
buff = strtok(NULL, " ");
int coursesNo = atoi(buff);
student studentList[studentsNo];
getStudentGrades(studentList, studentsNo, coursesNo);
displayFinalMatrix(studentList, studentsNo, coursesNo);
int bestStudent = findBestStudent(studentList, studentsNo);
printf("\nBest Student: STUDENT%0.2d\n", bestStudent + 1);
return 0;
}
void getArrayDimension(char* output, int size) {
FILE* data = fopen("data.txt", "r");
fgets(output, sizeof(char) * size, data);
fclose(data);
}
void getStudentGrades(student* studentList, int studentsNo, int coursesNo) {
char buffer[100];
char* mark;
FILE* data = fopen("data.txt", "r");
fgets(buffer, sizeof(buffer), data);
for (int i = 0; i < studentsNo; i++) {
fgets(buffer, sizeof(buffer), data);
mark = strtok(buffer, " ");
studentList[i].grades[0] = atoi(mark);
for (int j = 1; j < coursesNo; j++) {
mark = strtok(NULL, " ");
studentList[i].grades[j] = atoi(mark);
}
}
fclose(data);
}
void displayFinalMatrix(student* studentList, int studentsNo, int coursesNo) {
printf("Final marks matrix\n\t\t");
for (int i = 0; i < coursesNo; i++) {
printf("S%0.2d\t", i + 1);
}
printf("AVERAGE\n");
for (int i = 0; i < studentsNo; i++) {
printf(" STUDENT%0.2d", i + 1);
for (int j = 0; j < coursesNo; j++) {
printf("\t %d", studentList[i].grades[j]);
}
studentList[i].average = getAverage(studentList[i], coursesNo);
printf("\t %0.3f\n", studentList[i].average);
}
}
float getAverage(student currentStudent, int coursesNo) {
float total = 0;
for (int i = 0; i < coursesNo; i++) {
total += currentStudent.grades[i];
}
return (float)(total / coursesNo);
}
int findBestStudent(student* studentList, int studentsNo) {
int bestStudent;
float bestScore = -1;
for (int i = 0; i < studentsNo; i++) {
if (studentList[i].average > bestScore) {
bestStudent = i;
bestScore = studentList[i].average;
}
}
return bestStudent;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment