Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches For Loops

I have a problem with the for-loops-2 challenge in C# Why won't it compile?

namespace Treehouse.CodeChallenges { class FrogStats { public static double GetAverageTongueLength(Frog[] frogs) { for(int i = 0; i < frogs.TongueLength; i++) { Frog frog = frogs[i]; } } } }

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            for(int i = 0; i < frogs.TongueLength; i++)
            {
                Frog frog = frogs[i];
            }
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

3 Answers

Khoa Nguyen
Khoa Nguyen
4,735 Points

double avgTongueLength = 0d; double total = 0d; for(int i = 0; i < frogs.Length; i++) { total = total + frogs[i].TongueLength; } avgTongueLength = total / (frogs.Length -1 )

You have two errors in your GetAverageTongueLength method.

  1. You aren't returning a value. You need to return a double to satisfy the method signature.

  2. You are trying to access the TongueLength property of an instance of your Frog class instead of the Length property of the frogs array. If you want to iterate over all the elements in the frogs array you need to change frogs.TongueLength to frogs.Length, and then you can implement your logic to calculate the average tongue length within your for loop.

Dear Khoa Nguyen,

The Format in which the answer is returned does not comply with the way challenge requires it to return.

In your example it returns a single value; While the requested answer is in an arrayformat.

Kind Regards,

Fabian Pijpers.