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

Luis Paulino
PLUS
Luis Paulino
Courses Plus Student 1,779 Points

I know my problem is inside the for in loop, what can I do to improve the code?

I f*ck up with running the average, x float value, through runningTotal. It's does miner errors that trip me up, but this is just my second attempt so it's not too bad.

variable_assignment.mm
NSArray *temps= @[@75.5, @83.3, @96, @99.7];
float average;
float runningTotal;
for(NSNumber *temps in tempsArray ){ 
  float runningTotal( xfloatValue && flat avarage);
}

1 Answer

Hi Luis,

You've nearly done that - very close!

A few points to make. Here:

for(NSNumber *temps in tempsArray)

The loop will iterate over an array holding each value in the array, in turn, within the local variable declared there. Your array is called temps so you'll need to call your local variable something different. Just use x; it's easy! And tempsArray doesn't exist; change that to temps. That gives us:

for(NSNumber *x in temps){
  // add up all the x's
}

We want to add the value held by x into runningTotal at each iteration. You've got:

float runningTotal( xfloatValue && flat avarage);

First, don't redeclare runningTotal as a float; omit the float word as the compiler knows runningTotal is a float already. Next, ignore average for now - we come to that later. You can't create the average inside the loop. What we're doing is adding up all the elements of temps with the loop, we'll then divide by the length of temps after the loop and store the result of that in average.

Inside the loop, you want to add to runningTotal with += just like you have done. But we need to convert the NSNumber into float. Use square brackets and floatValue for that:

runningTotal += [x floatValue];

That completes the loop. It looks like:

for(NSNumber *x in temps){
  runningTotal += [x floatValue];
}

Now, find the number of elements in the temps array. Use the count property and square brackets again [temps count], and divide runningTotal by that. Store the result in average.

Let me know how you get on.

Steve.