C# C# Objects Loops and Final Touches Foreach Loops

Michael Thompson
Michael Thompson
7,427 Points

No idea where to even start.

Maybe a dumb question, and yes my code is basically me googling how to do this because I don't feel as if the instruction in any of the beginning C# track was done with the idea of actually teaching anybody C#, but where in the world is frogs.Length coming from? I do not for my life understand what it means when a this is being done. Too much terminology thrown at you way too quickly and with almost 0 explanation.

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double total = 0;

            foreach (Frog frog in frog)
            {
                total += frog.TongueLength;
            }
                return total / frogs.Length;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }
    }
}

2 Answers

james south
james south
Front End Web Development Techdegree Graduate 31,249 Points

the line

public static double GetAverageTongueLength(Frog[] frogs)

initiates the getAverageTongueLength method. it takes one argument when called, an array of Frogs. frogs is an internal variable or parameter in the method. Frog (capital F) is the type, frogs (lowercase f) is the parameter name. so frogs.length is the length of the array of Frogs passed in to the method when it is called.

Michael Thompson
Michael Thompson
7,427 Points

so .Length is just a keyword saying we want to run through the length of an array?

Erick R
Erick R
5,291 Points

Exactly. Suppose we have an array of 5 values. The Length will return 5 which is counted from 1-5. Take note that the Length keyword returns the actual count of the items and it does not start at 0 it starts at 1. So to get the last item in an array i would call this array[5].Length - 1; This statement will give me the item content located at index 4 of the array. Because Length returns all the values which is 5 but the last value that is indexed in the array is 4. 0-4(which is 5 items counted from 0). So in the problem above, you have an array being passed as the parameter. Each value contains an object that has a property called TongueLength. You add all these values up and store it in a variable iterating through each object in the array of objects called frogs. Finally, the average is the sum of all items divided by the number of items. So you would return the sum which you have stored in the variable divided by the Length of frogs(the amount of items in the array) and thus you end up with the average of TongueLength. Do not confuse this with the keyword sizeof. sizeof returns the total bytes of the array and not the actual count.