Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Moira Lawrie-Martyn
7,819 PointsBest way to handle an array and nested loops
Hey guys,
I'm struggling with an array and nested loops and wanted to bounce it off the community.
What I need to do is take an array of >50000 values and loop through it.
The first thing I need to do is capture the year of the value and group together all the values that have the same year
The second thing I need to do is for each year, group those into months
The third thing I need to do is average out the values in each month (easy part)
I was thinking something similar to:
year = array[0].year;
for(int i = 0; i < array.length; i++)
{
if(year == array[i].year)
{
month = array[i].month;
while(month = array[i].month)
{
average the values and collect into another array
}
month = array[i].month
}
else
{
year = array[i].year
}
}
But I dunno...the logic in my brain tells me this isn't gonna work and values are going to get skipped. I can't say "I'll just collect them into separate arrays" because that isn't extensible.
I can't hard code anything because I don't know what data is going to run through it once it's built but I'm seriously stuck here.
Can anyone give me some guidance here?
Thanks! <3
1 Answer

Steven Parker
216,071 PointsI assume you meant to have a comparison (==) instead of an assignment (=) in the "while" loop; but even so, unless one of the terms gets changed in the loop body that loop will never end.
But you shouldn't need a nested loop if you have a place (another array or a list) to accumulate sums and counts of each month/year. Then after the main loop finishes, a much shorter one could compute the averages, and output them (if desired).
Another thing you might consider as an alternative to a loop is a Linq query where you group by the month.