In this case, the data is strings instead of integers or floats, but tghe algorithm is the same:
initialize the max
get the first data
while there is more data
if the new data is larger than the max
update the max
get the next data
return (print) the max
To implement this algorithm, we need to measure the length of a string.
We could write our own utility to do this, or we can use strlen()
int strlen(char *s);
which returns the number of characters in the string, s.
while(*max_so_far++ = *data++);
or we can use
char *strcpy(char *target, char *src);
char *gets(char *s);
a function which reads a line of text from the standard input, replacing
the '\n' with '\0' (NULL). It returns the pointer, s, or NULL if end
of file or an error occurs.
To print the longest string, we can use
printf("%s\n", max_so_far);
or use the library function
int puts(char *s);
which has the same effect - print the string and a newline
to the stanard output.
#include <string.h>
#include <stdio.h>
#define MAX_STR 200
main()
{ char data[MAX_STR];
char max_so_far[MAX_STR] = "";
strcpy(max_so_far,"");
while(gets(data))
if(strlen(data) > strlen(max_so_far))
strcpy(max_so_far,data);
puts(max_so_far);
}
int strcmp(char *s, char *t);
This function compares the strings s and t, character by character,
and returns an integer: