Pages

Friday, 9 February 2018

Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:


#include<stdio.h>
#include<conio.h>


/* make a list of words, every words should be written under previous one to
   make sure it's a list of words. */


/* upper case letters will be arranged before small case letter, so it is
   recommended to use the list of either Capital letter or small case letters
   but not both together. */
struct word {
      char wrd [30];
      };

void main() {

struct word w[N];

FILE *fp;
char s1[30];
int i=0,count=0;
void srt_wrd();   /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {
strcpy(w[i].wrd,s1);  /* copying each word in array of structure */
i++;
count++;         /* count of all the words */
}

printf("Total words if file = %3d\n",count);


printf("\t\tList in alphabetical order:\n");
srt_wrd(&w,count);  /* function for sorting and printing list */


fclose(fp);
getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;
struct word temp;

/***************************************/
/* sorting words in alphabetical order */
/***************************************/

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {


/* testing the first alphabets of two words */

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}


/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}


/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}

 }
}

/*****************************/
/* printing the sorted words */
/*****************************/

for(i=0;i<n;i++) {

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");
getch();

k=1;
clrscr();
}
}


}