The Program in C to sort the names in a given list in ascending order is given below:
#include <stdio.h>
#include <string.h>
void bubbleSort(char names[][20], int n)
{
int i, j;
char temp[20];
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (strcmp(names[j], names[j+1]) > 0)
{
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
}
int main()
{
char names[10][20];
int i, n;
// Input the number of names
printf("Enter the number of names: ");
scanf("%d", &n);
// Input the names
printf("Enter the names: \n");
for (i = 0; i < n; i++)
{
scanf("%s", names[i]);
}
// Sort the names
bubbleSort(names, n);
// Print the sorted names
printf("Sorted names: \n");
for (i = 0; i < n; i++)
{
printf("%s\n", names[i]);
}
return 0;
}
Output:
Enter the number of names: 6
Enter the names:
DILLIRAM
JASHMAYA
KRISHNA
ARUNA
SRIJANA
KUMAR
Sorted names:
ARUNA
DILLIRAM
JASHMAYA
KRISHNA
KUMAR
SRIJANA
Pro-Tips💡
The program uses the bubble sort algorithm to sort the names in ascending order.
The function bubbleSort()
takes an array of strings (i.e., char names[][20]
) and its size as arguments, and sorts the array in ascending order using nested loops and the strcmp()
and strcpy()
string library functions to compare and swap names.
The main function first takes the number of names as input, then takes the names as input and stores them in an array.
Then it calls the bubbleSort()
function to sort the names, and finally it prints the sorted names.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.