string - first and last words in alphabetical order in c -
this c prog takes 5 words separated spaces , gives first , last word acc alphabetical order. eg.enter 5 words: banana ap pa kiwi orange. first word=ap last word=pa.no error shown prog isn't working, more 5 words being accepted.this code:
void findword(char word[][20], char *first, char *last); int main() { char word[5][20]; char *first, *last; printf("enter 5 words separated spaces: \n"); (int = 0; < 5; i++) { (int j = 0; j < 20; j++) scanf("%c", &word[i][j]); } first = word[0][0]; last = word[0][0]; findword(word, &first, &last); printf("the first word is: %s , last word is: %s ", first, last); } void findword(char word[][20], char *first, char *last) { int k, l; (k = 0; k < 5; k++) { (l = 0; l < 20; l++) { while ((word[k][l] != '\0') && (word[k][l] == ' ')) { if (word[k][l + 1]< *first) *first = word[k][l + 1]; else *last = word[k][l + 1]; } } } }
try this
#include<stdio.h> #include<string.h> void findword(char word[][20], char *first, char *last); int main() { char word[5][20]; char first[20], last[20]; int i,j; printf("enter 5 words separated spaces: \n"); (i = 0; < 5; i++) { scanf("%s", word[i]); } strcpy(first,word[0]); strcpy(last,word[0]); findword(word, first, last); printf("the first word is: %s , last word is: %s ", first, last); } void findword(char word[][20], char *first, char *last) { int k; (k = 0; k < 5; k++) { if(strcmp(word[k], last)>0) strcpy(last,word[k]); else if(strcmp(word[k],first)<0) strcpy(first,word[k]); } }
Comments
Post a Comment