This blog is under construction

Monday 15 July 2013

C program to sort characters of a string in descending order

Write a C program to sort characters of a string in descending order.


  #include <stdio.h>
  #include <string.h>

  int main() {
        char myStr[256];
        int i, j, tmp;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(myStr, 256, stdin);
        myStr[strlen(myStr) - 1] = '\0';

        /* sort the characters of a string in descending order */
        for (i = 0; i < strlen(myStr) - 1; i++) {
                tmp = myStr[i];
                for (j = i + 1; j < strlen(myStr); j++) {
                        if (tmp < myStr[j]) {
                                tmp = myStr[j];
                                myStr[j] = myStr[i];
                                myStr[i] = tmp;
                        }
                }
        }

        /* Resultant output string */
        printf("Sorted Output String: %s\n", myStr);
        return 0;
   }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string: Significant                        
  Sorted Output String: tnniiigfcaS


No comments:

Post a Comment