/*
* Copyright 2023, Ali Arya
* Anyone Can Code: Algorithmic Thinking
* Example 5.7c
*/

#include <iostream>
#include "string.h""
using namespace std;

#define NUM_GRADES   5
#define NUM_STUDENTS 5

struct Student
{
    char name[50];
    int ID;
    int grades[NUM_GRADES];
    int average;
};

void StudentInfo(Student s)
{
    cout << s.name << "\t";
    cout << s.ID << "\t";
    for (int i = 0; i < NUM_GRADES; i++)
        cout << s.grades[i] << "\t";
    cout << s.average << "\n";
}

int main()
{
    //create and initialzie a random set of student info
    Student s[NUM_STUDENTS];
    for (int i = 0; i < NUM_STUDENTS; i++)
    {
        s[i].ID = rand() % 900 + 100;
        strcpy_s(s[i].name, 50, "x");
        s[i].average = 0;
        for (int j = 0; j < NUM_GRADES; j++)
        {
            s[i].grades[j] = rand() % 100;
            s[i].average += s[i].grades[j];
        }
        s[i].average /= NUM_GRADES;
    }

    //print student data
    cout << "Student data before sorting:\n";
    cout << "Name" << "\t" << "ID" << "\t" << "g1" << "\t" << "g2" << "\t" << "g3" << "\t" << "g4" << "\t" << "g5" << "\t" << "average\n";
    cout << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------\n";
    for (int i = 0; i < NUM_STUDENTS; i++)	//loop over all students
        StudentInfo(s[i]);

    //sort by ID
    for (int i = 0; i < NUM_STUDENTS; i++)
        for (int j = i; j < NUM_STUDENTS; j++)
        {
            if (s[i].ID < s[j].ID)
            {
                Student temp;
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
        }

    //print data again
    cout << "\n";
    cout << "Student data after sorting by ID:\n";
    cout << "Name" << "\t" << "ID" << "\t" << "g1" << "\t" << "g2" << "\t" << "g3" << "\t" << "g4" << "\t" << "g5" << "\t" << "average\n";
    cout << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------" << "\t" << "------\n";
    for (int i = 0; i < NUM_STUDENTS; i++)	//loop over all students
        StudentInfo(s[i]);



    return 0;
}
