C# C# Objects Loops and Final Touches Foreach Loops

Thomas Newton
PRO
Thomas Newton
Pro Student 2,442 Points

Not sure what I need to do here

I vaguely understand what is being asked of me here, but I'm not entirely sure how to apply the foreach loop in this instance. If someone could demonstrate this for me, that would be appreciated.

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

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

2 Answers

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

I really wish I knew what you'd tried that's failing so that I could more precisely direct you to help about where you're going wrong or concepts you're not understanding fully. But let me try and explain this challenge maybe a little more clearly than they have.

Let's say that you're some sort of expert on frogs/amphibians or something. And a zoo is going to send you a box of frogs. Now you have no idea how many frogs are going to be in that box. Just... a lot of frogs. And as part of this super strange scenario you're now going to have to get the average length of tongue for all those frogs. So what you do first is accept the box of frogs. Then you open it and you number them starting at 0. Now you start at 0 and measure that frog's tongue. And the next... and next.. until you're done. Then you take the total length of all the frogs' tongues put together and divide it by the total number of frogs. And here's how that would look in code with a foreach loop.

namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)  //declare a method to take an array of objects with type Frog
        {
            double totalLength = 0.0;  // set the total length to 0
            foreach (Frog frog in frogs) {  //for every frog in our frog array
                totalLength += frog.TongueLength;  //add the length of that frog's tongue to our total length
            }
            return totalLength / frogs.Length;  //return the average frog tongue length by dividing the total length by the number of frogs
        }
    }
}

I included notes in the comments to explain what's going on. Hope this helps! :smiley:

Severin Haselmann
Severin Haselmann
21,377 Points

Thank you Jennifer Nordell for this perfect explanation! I got stuck here as well >-< . Your comments made foreach loop crystal clear! ; )

Thomas Newton
PRO
Thomas Newton
Pro Student 2,442 Points

Managed to solve it with some outside help, Thanks!