Array of Strings
Completed
Read n words into a 2D char array and print the longest word and the alphabetically first word.
Input
n, then n words (each under 30 letters).
Output
Two lines.
Example
Input
5 pear banana fig kiwi apple
Output
banana apple
Editor
C
Hints
char words[20][30] holds 20 strings of up to 29 characters.
Track indexes rather than copying strings.
Solution explanation
Keeping the index of the best word avoids copying strings around.
Show solution
#include <stdio.h>
#include <string.h>
int main() {
int n;
char words[20][30];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%s", words[i]);
int longest = 0, first = 0;
for (int i = 1; i < n; i++) {
if (strlen(words[i]) > strlen(words[longest])) longest = i;
if (strcmp(words[i], words[first]) < 0) first = i;
}
printf("%s\n%s\n", words[longest], words[first]);
return 0;
}