This is what I’m up to so far
char max = 0, here;
while(scanf("%c", &here) == 1 && here != '\n')
if(here > max)
max = here;
printf("max='%c'\n", max);
The user could enter a sequence of characters, and I’d get back the letter with the highest ASCII value. In Computer Fun, this would be u. But if CompUter Fun were the input, I’d want to get U back because it has been entered first in the sequence.
I could have two variables saving the highest capital letter and the highest simple letter, but how would I then know which came first?
Thanks in advance. Explaining the logic is just fine, if you don’t want to write out the code fragment that does this.
You only need one variable—just keep track of the character that wins up to this point.
As you scan over the input
CompUter Fun, you first seeC. Since its the first character, its the winner so far. Then you seeo.ocomes afterC, so its now the winner; your variable now containso. And so on. You only replace the stored character if the new one wins, so you’ll get the first one in case of ties.(When comparing, you need to do a case-insensitive compare; an easy way to do this is
toloweron both sides of the compare).gives the ultimate winner, U.
This is an efficient general algorithm for finding the maximum (or minimum, by reversing the compare) of an unordered input. It can also be extended to keep track of 2nd (etc.) place, though at some point sorting becomes more efficient, especially on data like this where you can use radix O(n) sorts.