C Program to Read Records of n Different Students in Structure & Sort on the Basis of Marks in Ascending Order

C program to read records of n different students in structure having member name, roll and marks, and displaying the student details which are sorted by marks in ascending order.

C Source Code: Read Records of n Students & Sort Marks in Ascending Order


#include<stdio.h>

/* Declaration of structure */
struct student
{
 char name[30];
 int roll;
 float marks;
};

int main()
{
/* Declaration of array of structure */
 struct student s[20], temp;
 int i,j,n;
 
 printf("Enter n:\n");
 scanf("%d",&n);
 for(i=0;i< n;i++)
 {
  printf("Enter name, roll and marks of student:\n");
  scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks);
 }
 for(i=0;i< n-1;i++)
 {
  for(j=i+1;j< n;j++)
  {
   if(s[i].marks>s[j].marks)
   {
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
   }
  }
 }
 printf("Sorted records are:\n");
 for(i=0;i< n;i++)
 {
  printf("Name: %s\n", s[i].name);
  printf("Roll: %d\n", s[i].roll);
  printf("Marks: %0.2f\n\n", s[i].marks);
 }
 return 0;
}

Output

The output of the above program is:

Enter n:
4 ↲
Enter name, roll and marks of student:
Ram ↲
10 ↲
88 ↲
Enter name, roll and marks of student:
Shyam↲
11 ↲
67 ↲
Enter name, roll and marks of student:
Hari ↲
12 ↲
92 ↲
Enter name, roll and marks of student:
Prakash ↲
13 ↲
88.5 ↲
Sorted records are:
Name: Shyam
Roll: 11
Marks: 67.00

Name: Ram
Roll: 10
Marks: 88.00

Name: Prakash
Roll: 13
Marks: 88.50

Name: Hari
Roll: 12
Marks: 92.00

Note: ↲ indicates ENTER key is pressed.