It's because a variable remembers the length of the word each iteration. If the word in an iteration is larger than the largest length seen in iterations before, this becomes the new length.
Its easy to see this happening when logging each iteration:
Online sample: https://dotnetfiddle.net/oFBicx
public class Program
{
public static void Main()
{
var longestWord = returnLongestWord(new []{ "word1", "word12", "word1234", "mostdefinitelythelongestword!", "aShorterWord", "anotherShortWordThanTheMax"});
Console.WriteLine("\nDone - longest word: " + longestWord);
}
public static string returnLongestWord(string[] words)
{
string maxWord = "";
int ctr = 0;
foreach (var word in words)
{
if (word.Length > ctr)
{
maxWord = word;
ctr = word.Length;
}
Console.WriteLine("ctr: " + ctr + ", for word:\t " + maxWord);
}
return maxWord;
}
}
outputs:
ctr: 5, for word: word1
ctr: 6, for word: word12
ctr: 8, for word: word1234
ctr: 29, for word: mostdefinitelythelongestword!
ctr: 29, for word: mostdefinitelythelongestword!
ctr: 29, for word: mostdefinitelythelongestword!
Done - longest word: mostdefinitelythelongestword!
This function can be writter a bit differently however, whilst still achieving the same, in a manner that is a bit easier to read. Right now both the maximum length of a string is kept in a variable ctr
and the word for this length is remembered in maxWord
. However, since we can calculate the length of the largest word we found, we don't need to remember this. In our condition we can then recalculate the length and use that to compare it to the current word instead:
online sample2: https://dotnetfiddle.net/4C7eZB
public static void Main()
{
var longestWord = returnLongestWord(new []{ "word1", "word12", "word1234", "mostdefinitelythelongestword!", "aShorterWord", "anotherShortWordThanTheMax"});
Console.WriteLine("\nDone - longest word: " + longestWord);
}
public static string returnLongestWord(string[] words)
{
string largestWordFound = string.Empty;
foreach (var word in words)
{
if (word.Length > largestWordFound.Length)
{
largestWordFound = word;
}
Console.WriteLine("Largest word length: " + largestWordFound.Length + ", for word:\t " + largestWordFound);
}
return largestWordFound;
}
outputs:
Largest word length: 5, for word: word1
Largest word length: 6, for word: word12
Largest word length: 8, for word: word1234
Largest word length: 29, for word: mostdefinitelythelongestword!
Largest word length: 29, for word: mostdefinitelythelongestword!
Largest word length: 29, for word: mostdefinitelythelongestword!
Done - longest word: mostdefinitelythelongestword!