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 Objective-C Basics Scope and Loops For Loop

Ryan Maneo
Ryan Maneo
4,342 Points

1275?

In the video, it has a value of running total as 1275 after it finished its last iteration of the loop, why? Where the heck did 1275 come from?

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points
int runningTotal = 0;

for (int = 1; i <= 50; i++) {
   runningTotal = runningTotal + i
}

the for loop will iterate over the numbers 1 to 50. With every loop the runningTotal is not incremented by the index, but runningTotal + 1. So the calculations would look like this:

// runningTotal = runningTotal + i

runningTotal = 0 + 1 // runningTotal is 0
runningTotal = 1 + 2 // runningTotal is now 3
runningTotal = 3 + 3 // runningTotal is now 6
runningTotal = 6 + 4 // runningTotal is now 10
// etc

So I have not calculated that through, but my guess is that runningTotal will be 1275 in the end.

Hope that helps :)