MIT-Curricular/DS/C/Lab/Week2/StructureStudent.c

61 lines
1.5 KiB
C

#include <stdio.h>
typedef struct {
char name[50];
int roll_no;
char grade;
} student;
void read_students(student students[], int n) {
for (int i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll No: ");
scanf("%d", &students[i].roll_no);
printf("Grade: ");
scanf(" %c", &students[i].grade);
}
}
void display_students(student students[], int n) {
printf("\nStudent Information:\n");
for (int i = 0; i < n; i++) {
printf("Name: %s, Roll No: %d, Grade: %c\n", students[i].name, students[i].roll_no, students[i].grade);
}
}
void sort_students_by_roll(student students[], int n) {
student temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (students[i].roll_no > students[j].roll_no) {
temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
student students[n];
read_students(students, n);
printf("\nBefore sorting:\n");
display_students(students, n);
sort_students_by_roll(students, n);
printf("\nAfter sorting by roll number:\n");
display_students(students, n);
return 0;
}