Structure Array Sorter
C
Hard
2 views
Problem Description
Create an array of student structures. Create a sorting function that sorts based on marks. Implement bubble sort with structure swapping.
Official Solution
#include <stdio.h>
#include <string.h>
// Student structure
struct Student {
int roll_no;
char name[50];
float marks;
};
// Function to swap two students
void swap(struct Student *a, struct Student *b) {
struct Student temp = *a;
*a = *b;
*b = temp;
}
// Bubble sort function based on marks
void sortByMarks(struct Student students[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (students[j].marks > students[j + 1].marks) {
swap(&students[j], &students[j + 1]);
}
}
}
}
// Function to display students
void display(struct Student students[], int n) {
printf("nSorted Student List (by Marks):n");
printf("Roll NotNamettMarksn");
for (int i = 0; i < n; i++) {
printf("%dt%stt%.2fn", students[i].roll_no, students[i].name, students[i].marks);
}
}
int main() {
int n;
printf("Enter number of students: ");
scanf("%d", &n);
struct Student students[n];
// Input student details
for (int i = 0; i < n; i++) {
printf("nEnter details for student %d:n", i + 1);
printf("Roll No: ");
scanf("%d", &students[i].roll_no);
printf("Name: ");
scanf(" %[^n]", students[i].name); // allows spaces
printf("Marks: ");
scanf("%f", &students[i].marks);
}
// Sort students by marks
sortByMarks(students, n);
// Display sorted list
display(students, n);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!