Write a program to sort the strings according to its length.
#include<stdio.h> #include<stdlib.h> #include<string.h> void Sort_by_length(char**); int main() { char **p,temp[100]; int n,i,j; printf("How Many strings do you want ? "); scanf("%d",&n); p = (char**)malloc(sizeof(char*)*n); for(i = 0;i < n;i++) { p[i] = (char*)malloc(100); } printf("Enter %d strings\n",n); for(i = 0;i < n;i++) { scanf(" %[^\n]",p[i]); } printf("\nOriginal Strings\n"); for(i = 0;i < n;i++) { printf("%s\n",p[i]); } Sort_by_length(p); printf("\nSorted Strings\n"); for(i = 0;i < n;i++) { printf("%s\n",p[i]); } } void Sort_by_length(char **p) { char temp[100]; int i,j; for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(strlen(p[i]) > strlen(p[j])) { strcpy(temp,p[i]); strcpy(p[i],p[j]); strcpy(p[j],temp); } } } }
Output
How Many strings do you want ? 6 Enter 6 strings Lot To Learn I Start Incredible Original Strings Lot To Learn I Start Incredible Sorted Strings I To Lot Learn Start Incredible