C# C# Objects Loops and Final Touches Foreach Loops

Travis John Villanueva
Travis John Villanueva
5,052 Points

returning a value from a for each loop

Can you correct my code and i will digest it from there?

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            foreach(Frog frog in frogs)
            {
                return frog.TongueLength;
            }
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

Steven Parker
Steven Parker
177,538 Points

You might have a better learning experience if you fix it yourself.

Here's a few hints that may help:

  • don't return inside the loop, that means the loop can never go past the first item
  • you probably want to declare a variable to collect a total length before the loop
  • inside the loop, you might want to add the frog's length to the total
  • after the loop, if you divide that total by the number of frogs you could get an average
  • then you could return that average