- 2070 Asar · 6 marks
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)
Related questions
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Student records file with CRN search · Object Oriented Programming, chapter 8
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Write and display 10 employees using file · Object Oriented Programming, chapter 8
- Abstract Student class program · Object Oriented Programming, chapter 7
- Pass student array; display passed students · Computer Programming, chapter 7
- 96 students record; pass marks · Computer Programming, chapter 10
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Normal: IOE marks of 5000 students · Probability and Statistics, chapter 3