In this program, you'll learn to sort the students structure using pointers.
#include<stdio.h>
struct student
{
int rollno;
char name[10];
char branch[10];
};
void swap(struct student *, struct student *);
void main()
{
struct student s[3];
struct student *ptr = NULL;
int i, j;
ptr = s;
for(i=0; i<3; i++){
printf("\nEnter details of Student #%d\n", i+1);
printf("Enter roll no: ");
scanf("%d", &ptr->rollno);
printf("Enter name: ");
scanf("%s", ptr->name);
printf("Enter branch: ");
scanf("%s", ptr->branch);
ptr++;
}
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
if(s[j].rollno > s[j+1].rollno)
{
swap(&s[j], &s[j+1]);
}
}
}
ptr = s;
printf("\nAfter sorting students by roll no..\n");
for(i=0; i<3; i++)
{
printf("\n%d %10s %10s", ptr->rollno, ptr->name, ptr->branch);
ptr++;
}
getch();
}
void swap(struct student *a, struct student *b)
{
struct student temp;
temp = *a;
*a = *b;
*b = temp;
}
Enter details of Student# 1
Enter roll no: 3
Enter name: Harsh
Enter branch: CO
Enter details of Student# 2
Enter roll no: 2
Enter name: Sudhir
Enter branch: IT
Enter details of Student# 3
Enter roll no: 1
Enter name: Laksham
Enter branch: CO
After sorting students by roll no..
1 Laksham CO
2 Sudhir IT
3 Harsh CO