Write a c program to store records of n students based on roll_no, name, gender and 5 subject marks Calculate percentage each student using 5 subjects., Display the student list according to their percentages
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a structure to represent a student
typedef struct {
int roll_no;
char name[50];
char gender;
int marks[5];
float percentage;
} Student;
// Function to read student details
void readStudent(Student *student) {
printf("Enter roll number: ");
scanf("%d", &student->roll_no);
printf("Enter name: ");
scanf(" %[^\n]%*c", student->name); // Read string with spaces
printf("Enter gender (M/F): ");
scanf(" %c", &student->gender);
printf("Enter marks for 5 subjects: ");
for (int i = 0; i < 5; i++) {
scanf("%d", &student->marks[i]);
}
}
// Function to calculate percentage
void calculatePercentage(Student *student) {
int total = 0;
for (int i = 0; i < 5; i++) {
total += student->marks[i];
}
student->percentage = total / 5.0;
}
// Function to display student details
void displayStudent(Student student) {
printf("Roll No: %d\n", student.roll_no);
printf("Name: %s\n", student.name);
printf("Gender: %c\n", student.gender);
printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%d ", student.marks[i]);
}
printf("\nPercentage: %.2f\n", student.percentage);
}
// Comparator function for qsort to sort students by percentage
int compareByPercentage(const void *a, const void *b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
return (studentB->percentage - studentA->percentage) * 100; // Multiply by 100 to avoid float comparison issues
}
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
Student *students = (Student *)malloc(n * sizeof(Student));
// Read student details and calculate percentages
for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
readStudent(&students[i]);
calculatePercentage(&students[i]);
}
// Sort students by percentage
qsort(students, n, sizeof(Student), compareByPercentage);
// Display student list sorted by percentage
printf("\nStudent list sorted by percentage:\n");
for (int i = 0; i < n; i++) {
displayStudent(students[i]);
printf("\n");
}
free(students);
return 0;
}
Comments
Post a Comment