Write a program that reads 10 words and stores them in an array of strings. write a function that sorts the 10 words lexicographically using the strcmp and strcpy functions. Display the sorted array.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 5
void sort(char A[SIZE][SIZE])
{
int i, j, min;
char aux[SIZE] = "";
// nb of steps
for (i = 0; i < SIZE - 1; i++)
{
min = i;
for (j = i + 1; j < SIZE; j++)
if (strcmp(A[j], A[min])<0)
min = j;
if (min != i)
{
strcpy(aux, A[min]);
strcpy(A[min], A[i]);
strcpy(A[i], aux);
}
}
}
void main()
{
char A[SIZE][SIZE];
int i, min;
for (i = 0; i < SIZE; i++)
{
printf("Enter word %d: ", i);
scanf("%s", A[i]);
}
sort(A);
printf("\n\n** After sorting ** \n");
for (i = 0; i < SIZE; i++)
{
printf("A[%d]=\"%s\"\n", i, A[i]);
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sequence values and ranks