C++ Program to Sort Students Using Pointers

In this program, you'll learn to sort the students structure using pointers.



Source Code
#include<iostream>
using namespace std;

struct student
{
    int rollno;
    char name[10];
    char branch[10];
};

void swap(struct student *, struct student *);

int main()
{
    struct student s[3];
    struct student *ptr = NULL;

    int i, j;
    ptr = s;

    for(i=0; i<3; i++){
        cout<<"\nEnter details of Student #" << i+1;
        cout<<"\nEnter roll no: ";
        cin>> ptr->rollno;
        cout<<"Enter name: ";
        cin>> ptr->name;
        cout<<"Enter branch: ";
        cin>> 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;

    cout<<"\nAfter sorting students by roll no..\n";
    for(i=0; i<3; i++)
    {
        cout<<"\n   " << ptr->rollno << "  " << ptr->name << "  " << ptr->branch;
        ptr++;
    }
    return 0;
}

void swap(struct student *a, struct student *b)
{
    struct student temp;

    temp = *a;
    *a = *b;
    *b = temp;
}
Output

Enter details of Student #1
Enter roll no: 1
Enter name: Sudhir
Enter branch: CO

Enter details of Student #2
Enter roll no: 8
Enter name: Dinesh
Enter branch: IT

Enter details of Student #3
Enter roll no: 5
Enter name: Fatima
Enter branch: EJ

After sorting students by roll no..

   1  Sudhir  CO
   5  Fatima  EJ
   8  Dinesh  IT