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

Giannis Kataras
Giannis Kataras
1,279 Points

Why code wont compile?

I have written this code for challenge where is the error exactly?

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

            for ( int index=0; index < frogs[index].TongueLength; index++)
            {
                final=final+frogs[index];
                final =final/frogs.TongueLength;
                return final;
            }
        }


        }
    }
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

Hello!

You're currently looping from 0 to the TongueLength of the first frog instead of the number of frogs. You should loop from 0 to the number of frogs in the frogs array.

On the other hand, you're returning the final variable at the first loop, not after it has finished, therefore it won't be able to sum all the tongue lengths and divide them at the end.

Let's take it step by step.

namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            // declare a variable to store the sum of the tongue lengths of all frogs to divide them to the number of frogs at the end
            int final = 0;

            // loop through all frogs to sum the tongue length of each in the --final-- variable
            for (int index=0; index < frogs.Length; index++) 
            {
                // each time it loops it adds the current frog.TongueLength to the final variable
                final = final + frogs[index].TongueLength;
            }

            // divide the sum of all tongue lenghts (final) to the number of frogs (frogs.Length)
            double result = final / frogs.Length;

            // return the result
            return result;
        }
    }
}

Hope it helped!