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

Ryan Silva
Ryan Silva
1,071 Points

How can I get the sum of the frog's tongue length?

In my for loop, I've been trying "int total = frogs[i]++;" to try and add the values of each frog's tongue length in each element of the array but it's been giving me an error and I'm not sure how to get it to work properly.

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

            double average = total / frogs.Length;
            return average;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

Steven Parker
Steven Parker
230,917 Points

Doing frogs[i]++ would try to increment the frogs themselves, which doesn't make sense.
And frogs.tongueLength[i]++ would try to increment the tongue length of each of several tongues.

But to add them together, you need to iterate through the frogs and access their lengths. So you'd want to use frogs[i].tongueLength which is the tongue length of each frog. Then to add them all to the total you might write total += frogs[i].tongueLength. Note that you can't use the addition assignment and declare the variable at the same time, so you'll want to initialize total to 0 before the loop starts.

Ryan Silva
Ryan Silva
1,071 Points

Awesome, that helped and I got it working. Thank you!!