Skip to main content

Student file displayed in descending marks order

Short answer

Write student records (roll, name, marks) to a binary file. Read them into an array, sort descending by marks (e.g., bubble sort), and display. This loads all records into memory for sorting.

Write a program that stores information of a students in a file and display the file's content in descending order according to their marks obtained.

Approach: write student records to a binary file, read them all back into an array, sort the array by marks in descending order (bubble sort), and display it.

#include <iostream>
#include <fstream>
using namespace std;

class Student {
    int roll;
    char name[30];
    float marks;
public:
    void getData() { cout << "Roll, Name, Marks: "; cin >> roll >> name >> marks; }
    void display() { cout << roll << "\t" << name << "\t" << marks << endl; }
    float getMarks() { return marks; }
};

int main() {
    Student s[50], temp;
    int n;
    cout << "Number of students: ";
    cin >> n;

    ofstream fout("marks.dat", ios::binary);
    for (int i = 0; i < n; i++) {
        s[i].getData();
        fout.write((char*)&s[i], sizeof(Student));
    }
    fout.close();

    ifstream fin("marks.dat", ios::binary);       // read back
    int count = 0;
    while (fin.read((char*)&s[count], sizeof(Student)))
        count++;
    fin.close();

    for (int i = 0; i < count - 1; i++)           // sort descending
        for (int j = 0; j < count - 1 - i; j++)
            if (s[j].getMarks() < s[j + 1].getMarks()) {
                temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp;
            }

    cout << "\nRoll\tName\tMarks (descending)\n";
    for (int i = 0; i < count; i++)
        s[i].display();
    return 0;
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →