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

iOS Object-Oriented Objective-C Tying it All Together Cumulative Review

What is the correct answer?

What am I doing wrong here? This code seems to work in Xcode to determine the average.

variable_assignment.mm
NSArray *temps = @[@75.5, @83.3, @96, @99.7];
float average;
float sum = 0;

    for (NSNumber *number in temps) {
        sum = sum + [number floatValue];
        average = sum/temps.count;
    }

3 Answers

This was one of the strangest things. The only error I could see with your code is that you were computing the average inside of the loop. So I tried this:

    NSArray *temps = @[@75.5, @83.3, @96, @99.7];
    float average;
    float sum;

    for (NSNumber *number in temps) {
        sum += [number floatValue];
    }
    average = sum/temps.count;

and the Editor said I was trying to redefine sum!!??

So I tried this:

    NSArray *temps = @[@75.5, @83.3, @96, @99.7];
    float average;
    float sumx;

    for (NSNumber *number in temps) {
        sumx += [number floatValue];
    }
    average = sumx/temps.count;

and the Editor accepted it. Wow!

Happy coding.

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

I encountered this as well. "sum" is not a reserved keyword as far as I know, so I am wondering if this has something to do with the code checker for the challenge. Maybe Gabe Nadel could provide some insight on why 'sum' produces an error.

:dizzy:

Gabe Nadel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Gabe Nadel
Treehouse Guest Teacher

Indeed, this was an issue with our code challenge engine. I've changed the question a bit so it should be ok going forward. Thanks y'all for helping to make this experience better and better!