-1
public static string returnLongestWord()
{
    string input = Console.ReadLine();
    string[] words = input.Split(' ');
    string maxWord = "";
    int ctr = 0;
    foreach (var word in words)
    {
        if (word.Length > ctr)
        {
            maxWord = word;
            ctr = word.Length;
        }
    }
    return maxWord;
}

My code basically locates the longest word in the users input.

The thing that is bugging me is the foreach loop. In general I imagine it goes through the array list of all the words.

Now the conditional loop if. I understand that if it is greater then 0 it is obviously a long word, but basically any word the user inputs is greater then 0, so how do these 2 loops determine the longest word ?

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 2
    When the loop reaches a word longer than 0, it sets `maxword` to that word and `ctr` to the length fo that word. So the next word in the array is compared to _that new_ length, not to 0. You might want to use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through the code line by line and watch the value of `ctr` change as longer words are found. – René Vogt May 05 '20 at 19:27
  • 1
    The foreach loop iterates over (goes through) all the words, and if you look carefully, the words length is assigned to the `ctr` variable, if it is greater than `ctr`s current value, which is zero at the beginning. So, the first word's length is assigned to ctr, and, continuing to iterate in the list, if the new word's length is bigger than the current value of ctr, this is assigned to it, and when the loop ends, ctr contains the max length – Oguz Ozgul May 05 '20 at 19:28
  • 6
    The next thing I would focus on is learning how to debug your code. You can attach the debugger, step through each line, and inspect state (variables, fields, etc). Doing that will give you more insight into what your code is *actually doing* which is more helpful then having to rely on what you *think* your code is doing especially when you are first starting out. – Igor May 05 '20 at 19:29
  • Here are a few of the many resources available: [Navigate through code with the Visual Studio debugger](https://learn.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger), [Learn to debug C# code using Visual Studio](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger), and [Debugging C# Code in Visual Studio | Mosh](https://youtu.be/u-HdLtqEOog). – Igor May 05 '20 at 19:29

2 Answers2

1

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!
sommmen
  • 6,570
  • 2
  • 30
  • 51
  • 1
    the second example might be a tad out of my league but the help is much appreciated! – Matas Mikelionis May 05 '20 at 19:52
  • @MatasMikelionis is there something concrete you don't understand? `string.Length` calculates the length of a string. So instead of remembering the maximum length (the `ctr` variable) in the first sample (it goes from 5 to 6 to 8 to 29) we can simply use `string.Length` instead of the `ctr` variable. Aside from this - you haven't accepted any answers - is there a reason why? what do you still need to get a statisfied answer? – sommmen May 06 '20 at 07:52
  • Basically you answered everything, do not want to frustrate you too much of my "newbieness" – Matas Mikelionis May 06 '20 at 19:22
  • @MatasMikelionis well if this question is finished, go ahead an mark an answer as accepted https://stackoverflow.com/help/accepted-answer – sommmen May 07 '20 at 07:01
-3

There is no if-loop or conditional loop. Only condition inside a loop. Those are perfectly normal. Usually you want to compare the values to something or do something with some of the values (processing)

This code seems to try to find the longest word. Doing so requires going through every word and comparing it to the previously longest word. This code stores the values for the previously longest word, using the variables maxWord and ctr. Both values are initialized for a Empty string, because the alterantive would be a ton of extra case handling in the if.

Note that you can do without ctr, and the name is actually somewhat problematic - sounding very similar to constructor. Just use maxWord.Lenght to compare it to the previous word lenght. But aside from that extra variable, that is also how I would do it.

foreach is a special variant of the for loop. It only goes forward, you got not indexer to manage and it can work with things like Enumerators. But the downside is that you can not change the collection while running over it. In this case the operation is purely reading, however - so no issues at all.

This is how I would change it:

public static string returnLongestWord()
{
    //Basic code to get some words from teh user
    //Could totally be left outside the function, just hand the array in as argument
    string input = Console.ReadLine();
    string[] words = input.Split(' ');

    //Let us start with a empty string as "longest Word"
    //That way I do not have to add a special case for the first word
    string maxWord = "";

    //Go over all strings in the collection of strings
    foreach (var currentWord in words)
    {
        //This string is beigger then the previous longest word. Guess it is the new longest word (thus far)
        if (currentWord.Length > maxWord.Lenght)
        {
            maxWord = currentWord ;
        }
    }
    //I am through all the words. So maxWord should now contain the longest word (or at least the first of them).
    return maxWord;
}
Christopher
  • 9,634
  • 2
  • 17
  • 31
  • Textarea misjudgement I guess :) (No dv from me by the way, assuming this is an error) – Oguz Ozgul May 05 '20 at 19:28
  • I see, so basically every time the foreach loop goes threw a word in the words array it stores to the variable, in my case ctr, and then compares them ? btw is programming the only way to learn programming, I know it sorta sounds retarded on my end, but what I meant were books and such, do they prove as useful as actual programming ? – Matas Mikelionis May 05 '20 at 19:34
  • @MatasMikelionis One namechange can help: `foreach (var currentWord in words)`. If the currentWord is longer then the previously longest word, it is the new longest word. On a tie, the previous word is kept. – Christopher May 05 '20 at 19:36
  • @MatasMikelionis I wrote a hpefully somewhat clear example. I added comments to explain it. – Christopher May 05 '20 at 19:41