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

I'm finding the whole objective c Looping principal confusing

So I'm currently going over this at the moment - http://teamtreehouse.com/library/objectivec-basics/functional-programming-in-c/while-do-while-loop

Now this is how I'm breaking it down as I'm struggling to workout what the guy is talking about (dont know if its just me but I don't feel its that well explained)

Am I right in thinking this? -

sum is 0 add 2 and i = 0

that equals 2

because i is less than 3 it carries on but it auto increments it so it now becomes 1

sum is now 2 but because the int value now goes to 4 you add 4 and 2 together to become 6 and because we also added 1 to i before it now becomes 1?

1 Answer

While loop:

A while loop runs as long as a condition is true. Say you had

i = 0;
sum = 0;
while ( i < 3) {

sum +=2;
i++;
}

First time the loop runs: I is 0, which is less than 3, perform the loop. Add 2 to sum (it is now 2, since it was 0 before) increment i by 1 (it is now 1)

Second time the loop runs: I is 1, which is less than 3, perform the loop. Add 2 to sum (it is now 4, since it was 2 before) increment i by 1 (it is now 2)

Third time the loop runs: I is 2, which is less than 3, perform the loop. Add 2 to sum (it is now 6, since it was 4before) increment i by 1 (it is now 3)

4th time the loop runs: i is 3, which is not less than 3. Dont perform the loop

The do while loop is the same as a while loop except for one thing: A do while loop will always run AT LEAST once

If you had

i = 2;
while (i < 2) {
i++;
}

The loop would not be performed because i is not less than 2.

The do while version of this loop would be run once, since first it performs whatever is in the do block regardless of the while condition. it would do whats in the do block, then check the condition to determine if it needs to continue looping or stop

i = 2;
do {
i++;
} while (i > 2);

Awesome, thanks dude!

no problem. If you have any more trouble with loops, step through each line of code like I did above, and after you have stepped through it and know the values of the variables, ask yourself "Does the loop get performed again or not". If it does step through it and change the values.