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 Review Scope and Loops

Not sure to understand how for loop iteration works.

Hi! I'm not sure to understand how can I increment my mathTotal integer inside a for loop. And after that, should the bool status ("true") be inside that for loop or juste after? I did some google searches on it but I cannot find a really useful explanation (and something to unstuck me in that exercice). Any help? Thanks!

variable_assignment.mm
int mathTotal;
bool isComplete;

for (int i = 5; i < 26; i++) {
  mathTotal = i;
}
isComplete = true;

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey David Jehl,

This is how the code you posted is working:

First, the loop sets a local variable of i, with an Int value of 5. This is your counter.

Next, the loop evaluates for a condition. This means the loop will continue to execute while i is less than 26. If the condition is true, the code inside the loops body will be executed. The code in the body sets the value of mathTotal to the current value of i for that iteration.

Then, once this code inside the loop body is finished executing, the loop will increment your counter according to the incrementor we specified. This is i++, which will increase the value of i by 1.

The loop will then evaluate for the condition again, and continue this process until the condition evaluates to false for the first time. When the condition evaluates to false, the loop stops executing, and your code continues down the normal flow of execution.

In your example, after the loop has finished executing, you are setting the isCompleted variable to true.

Yeah but, I don't know why, it seems that I have a syntax problem and I don't know where. Any idea? Thanks a lot!

Steven Deutsch
Steven Deutsch
21,046 Points

It looks like you're missing the opening curly brace for your loop.