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#

Steve Agusta
Steve Agusta
6,221 Points

foreach loops: I don't understand how to iterate through the array

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

        foreach(Frog frog in frogs)
        {
            sum += frogs[i].TongueLength;
        }

        average = sum/frogs.Length;
        return average;
    }
}

}

1 Answer

Steven Parker
Steven Parker
231,007 Points

:point_right: It looks like you mixed for and foreach loop syntax.

Inside your loop, you try to subscript frogs using an index named i, but you haven't declared an "i" variable. You might have created an "i" in a for loop, but since you used a foreach loop you created a "frog" variable instead.

So inside your loop, you probably want something like this:

            sum += frog.TongueLength;

In any future postings, be sure to include a link to the challenge page.

Steve Agusta
Steve Agusta
6,221 Points

Got it now, thanks! I knew it was something wrong with the syntax.