Design a C program to list the
students name in alphabetical
order.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//create an array of names
char names[100][30];
int totalStudents=0;
int i,j;
char temp[30];
printf("Enter the number of students: ");
scanf("%d",&totalStudents);
fflush(stdin);
//Inputting names
for(int i=0; i<totalStudents; i++){
printf("Enter the name of student %d: ", (i+1));
gets(names[i]);
}
//Sort array using the Buuble Sort algorithm
for(i=0; i<totalStudents; i++){
for(j=0; j<totalStudents-1-i; j++){
if(strcmp(names[j], names[j+1]) > 0){
//swap array[j] and array[j+1]
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
//display the sorted array
printf("Sorted students names:\n");
for(int i=0; i<totalStudents; i++){
printf("%s\n", names[i]);
}
getchar();
return 0;
}
Comments
Leave a comment