Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128P)
* Instructor: Abdullahi Adem | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Define the student structure
struct s
{
char n[2][100]; // modified to be an array of strings
char i[100]; // added a field for the student ID
int m;
};
// Function to compare two students by name
int c(const void *d, const void *e)
{
struct s *o = (struct s *)d;
struct s *n = (struct s *)e;
// compare the last names first, then the first names
int l = strcmp(o->n[1], n->n[1]);
if (l != 0)
{
return l;
}
else
{
return strcmp(o->n[0], n->n[0]);
}
}
int main()
{
// Read in the number of students
int d;
printf("Program to create a student structure having fields studname, ID and mark. Accept the details of 'n'
students, rearrange the data in alphabetical order of student name and display it.");
printf("Enter the number of students: ");
scanf("%d", &d);
// Create an array of students
struct s m[d];
// Read in the details of each student
for (int o = 0; o < d; o++)
{
printf("\tEnter the first and last name, ID, and mark for student %d: ", o + 1);
scanf("%s %s %s %d", m[o].n[0], m[o].n[1], m[o].i, &m[o].m);
}
// Sort the students by name using the compare function
qsort(m, d, sizeof(struct s), c);
// Print the sorted list of students
printf("\nSorted list of students:\n");
for (int o = 0; o < d; o++)
{
printf("\t %s %s %s %d\n", m[o].n[0], m[o].n[1], m[o].i, m[o].m);
}
return 0;
}
Output
Program to create a student structure having fields studname, ID and mark. Accept the details of 'n'
students, rearrange the data in alphabetical order of student name and display it.
Enter the number of students: 2
Enter the first and last name, ID, and mark for student 1: Vanshaly Mohanan, XYZ309, 99
Enter the first and last name, ID, and mark for student 2: Divya Mohan, ABCD1234, 98
Sorted list of students:
Divya Mohan, ABCD1234, 98
Vanshaly Mohanan, XYZ309, 99