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

Christian A. Castro
Christian A. Castro
30,501 Points

When the loop finishes running, the value of 'average' should be the average of the values contained in temp. HELP!!

This is Challenge Task 2 of 2

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

float average
float runningTotal;

for (NSNumber x in temps)
{
    average = temps[x floatValue];
}
variable_assignment.mm
NSArray* temps = @[@75.5, @83.3, @96, @99.7];

float average  
float runningTotal; 

for (NSNumber x in temps)
{
  average = temps[x floatValue];
}

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

3 things:

  1. There's a syntax error on line 3 of your answer (the one where you declare average). Remember that every statement that's not a block declaration must end in a semicolon (;)

  2. Remember that in Objective-C, you always pass around pointers to Objective-C objects (not structs, though). In your for loop, you have x declared to be an NSNumber, and not a pointer to an NSNumber (NSNumber *), but it should be the other way around

  3. You have a syntax error on line 8 in your answer (the only one inside the for loop). You're using both subscript and method call syntax at the same time. Subscript syntax takes the name of the collection you're accessing on the left of the opening square bracket ([), and then the key within the square brackets ([]). For arrays, this is always some kind of numerical, but for dictionaries, it can be any NSObject or subclass. Method call syntax takes the object on which you're calling a method on the inside of the opening square bracket ([), then one or more whitespace characters (such as a space), then the method which you're calling, and then the closing square bracket (]). In this case, NSFastEnumeration automatically sets x to be the object you're currently inspecting, so you don't need to directly reference temps yourself directly within the loop

  4. Think about what an average is, and why the runningTotal variable exists. An average is the total of all numbers in a list, divided by the count of numbers in the list. In order to pass this challenge, you need to:

    • add all the numbers in temps together
    • divide the total by the count of numbers in temps
    • set that result to the average variable

Once you do those 4 things, you'll pass the challenge