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

Computer Science

Moira Lawrie-Martyn
Moira Lawrie-Martyn
8,073 Points

Best 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
Steven Parker
231,269 Points

I 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.