C program to print Strings in ascending order

Ex: Write a C program to print Strings in ascending order. How to write a C program to print Strings in ascending order. C program to print Strings in ascending order. 

Input from user:
Enter the number: 5
Enter the strings:
java
css
html
python 
ruby

Expected output:
Sorted strings are:
css
html
java
python
ruby



In below program to print strings in ascending order we will use string functions but, first we need to declare <string.h> header file in our program because, these string functions are defined in this <string.h> header file.


    Quick links:






Program:

#include<stdio.h>
#include<string.h>
void main()
{
   int i,j,no;
   char a[20][20],temp[20];
   /*Accept input number from  user*/
   puts("Enter the number:");
   scanf("%d",&no);

   /*Accept strings using gets() string function and store it in array a*/
   puts("Enter strings:");
   for(i=0;i<=no;i++)
      gets(a[i]);

   for(i=0;i<=no;i++)
   {
      for(j=i+1;j<=no;j++)
      {
         /*Compare two strings using strcmp() string function*/
         if(strcmp(a[i],a[j])>0)
         {
            /*Copy one string to another string using strcpy() string function*/
            strcpy(temp,a[i]);
            strcpy(a[i],a[j]);
            strcpy(a[j],temp);
         }
      }
   }
   /*Print sorted strings using puts() string function*/
   printf("\nSorted Strings are:");
   for(i=0;i<=no;i++)
      puts(a[i]);
   
}

Above program shows the following output:

C program to print Strings in ascending order

No comments:

Post a Comment

If you have any doubts, please discuss here...👇