Write a C program which will accept multiple strings fron the user and will sort them in ascending order.
#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char *str[5],*temp; int i,j,n; printf("\nHow many names do you want to have?"); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n Enter the name %d: ",i); flushall(); gets(str[i]); } for(i=0;i<n;i++) { for(j=0;j<n-1;j++) { if(strcmp(str[j],str[j+1])>0) { strcpy(temp,str[j]); strcpy(str[j],str[j+1]); strcpy(str[j+1],temp); } } } printf("nSorted List : "); flushall(); for(i=0;i<n;i++) puts(str[i]); return(0); }
Output :
How many names do you want to have? 4 Enter the name 0: pri Enter the name 1: prt Enter the name 2: prq Enter the name 3: pra Sorted List : pra pri prq prt
Explanation :
We are checking each successive strings using strcmp() function.
if(strcmp(str[j],str[j+1])>0) { strcpy(temp,str[j]); strcpy(str[j],str[j+1]); strcpy(str[j+1],temp); }
If string is greater than the successive string then we are swapping the strings.
No comments:
Post a Comment