In this tutorial we are going to learn writing C program to sort the characters of string in descending order. Here we will follow the insertion sort algorithm to sort the characters.
You can check out c program to sort character of string in ascending order
Program in C to sort the character of String in descending order
#include <stdio.h>
#include <string.h>
int main() {
char str[100], temp;
int i, j, len;
printf("=== C Program to Sort Characters in Descending Order ===\n");
printf("Please enter the string: ");
scanf("%[^\n]", str); // Takes input until a newline is encountered
len = strlen(str);
// Bubble sort logic to sort characters in descending order
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (str[i] < str[j]) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
printf("After sorting characters in descending order: %s\n", str);
return 0;
}
Output
=== C Program to Sort Characters in Descending Order ===
Please enter the string: quescol
After sorting characters in descending order: usqolec
What did you think?