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 (Retired) Functional Programming in C Control Flow - For Loops

Order of condition processing and "sub" term.

I have 2 questions:

1: There are three conditions that are run through before the sum and print statements; setting a variable (i) to 0, checking if i is less than 3 and incrementing the value of i.

Why are all three not activated when the loop starts; i.e:

  • start loop
  • i = 0, it's less than 3, i = 1
  • sum (1 + array number 1 (4) = 5
  • print 5

Instead, it seems like it leaves i at 0, skips the incrementing and goes right to the sum statement. But it DOES increment on the next loop.

Why is that?

2: At 2:20 Doug says "sub i" when referring to using the value of the i variable to index the array. What does the "sub" term mean?

Thanks very much.

1 Answer

Tom Holland
Tom Holland
24,288 Points

Hi Andrew,

When using a for loop, the code in parenthesis is called a "control statement." It describes how "the loop" will be set up. It does not actually modify any code or set any values other than the value of the index variable.

The value of i gets changed after each successful loop iteration, not inside the loop or before the code runs.

Here is what the for loop is supposed to do, given the (i=0;i<3;i++) control statement:

  • Set i = 0
  • Evaluate the conditional i < 3
  • Open the loop if true(exit if false or i > 3)
  • Do the code between braces (sum operation)
  • Increment the index
  • Re-evaluate the conditional and start another iteration if true, exit and close the loop if false.

Does that help clarify it?

As far as your second question... A for loop is an subroutine. The value of i changes with every iteration of the subroutine. I believe "sub i" is shorthand for the value of the index variable within a particular iteration of a subroutine.

Hope that helps!

Tom