Arrange student data in alphabetical order in C
Problem Statement: Arrange student data in alphabetical order in C
Student struct is used as a user-defined data type for student information.
stud[] array belongs to the student struct which will hold the student information.
sort() function will sort the stud[] array based on the student name in alphabetic order.
/*C program to Arrange student data in alphabetical order*/ #include<stdio.h> #include<string.h> #include<stdlib.h> struct student{ char name[20]; int roll; float marks; }; struct student stud[50]; int no; void accept(){ int i,j,k; printf("Total number of students:\t"); scanf("%d",&no); for(i=0;i<no;++i){ printf("stud %d=\n",i+1); printf("Name\tRoll\tMarks\n"); scanf("%s\t%d\t%f", stud[i].name,&stud[i].roll,&stud[i].marks); } } void display(){ int i; printf("Name\tRoll\tMarks\n"); for(i=0;i<no;++i){ printf("%s \t%d \t%.2f\n", stud[i].name,stud[i].roll,stud[i].marks); } } void swap(int s1, int s2){ char t_name[20]; strcpy(t_name,stud[s1].name); strcpy(stud[s1].name,stud[s2].name); strcpy(stud[s2].name,t_name); int t_roll; t_roll=stud[s1].roll; stud[s1].roll=stud[s2].roll; stud[s2].roll=t_roll; float t_marks; t_marks=stud[s1].marks; stud[s1].marks=stud[s2].marks; stud[s2].marks=t_marks; } void sort(){ int i,j,k; for(j=1;j<=no;++j) for(i=j-1;i>=0;--i){ if(strcmp(stud[i-1].name,stud[i].name)>0){ swap(i-1,i); } } } int main(){ accept(); display(); sort(); printf("Sorted Student data:\n"); display(); }
$ gcc sort.c $ ./a.out Total number of students: 2 stud 1= Name Roll Marks pqr 1 100 stud 2= Name Roll Marks abc 2 100 Name Roll Marks pqr 1 100.00 abc 2 100.00 Sorted Student data: Name Roll Marks abc 2 100.00 pqr 1 100.00 $ |
also see
C Programming language |
Go Programming language |
Linked List | Array |
Simplification | Queue |
DBMS | Reasoning |
Aptitude | HTML |