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

Michael Castro
Michael Castro
11,959 Points

Finding the average of NSNumbers in an array with a for loop.

Create a float variable called runningTotal. Then, create a for in loop which iterates through the array you created in step 1. When the loop finishes running, the value of 'average' should be the average of the values contained in temp.

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

for (NSNumber *t in temps, t < temps.count, t++) {
  runningTotal = (runningTotal + t);
  average = runningTotal/temps.count;}

/*
for (NSUInteger *t in temps, t < temps.count, t++) {
  runningTotal += [[temps objectAtIndex:t] floatValue];
  average = runningTotal/temps.count;
}
*/
//NSNumber * average = [temps valueForKeyPath:@"@sum.self"];

1 Answer

sonu dhawan
sonu dhawan
1,989 Points
NSArray *temps = @[@75.5, @83.3, @96, @99.7]; // YOU DON'T NEED TO PUT DECIMALS OR INTS INSIDE PARENTHESIS
float average ; // IF YOU ARE GIVEN  IN THE QUESTION NOT TO INITIALIZE THE VARIABLE "make yourself go exactly with the command what they were asking you to do " . 
float runningTotal ;

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

average = runningTotal/temps.count;