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 Swift Basics (retired) Control Flow For-Condition-Increment

Shayan Khan
Shayan Khan
9,842 Points

I don't understand where and why do we need to increment in loops

I don't get the concept of incrementing in loops.

1 Answer

Hiya,

The increment is used to 'bounds-check' the progress of the loop - this enables it to know when to stop looping.

So, say we're looping through an array of strings like ["One", "Two", "Three", "Four"] which has four elements (0 .. 3). We only want to read each element once so we'd use a simple for loop with a counter to access the array element. This could look something like array[count].

The count variable would be initialised to zero at the start of the loop meaning that on the first ieteration of the loop, the array's first element would be read: array[count] is the same as array[0]. When we've read that, the loop completes its first pass and starts its second. We don't want to read array[0 again (else we'll be here a long time!) so we increment count by saying count++. So on this pass, we now access array[1] - the next pass we get array[2] and so on.

In the for loop, we also test for the end of the loop. We don't let count get larger than the number of elements in the array so the loop ends when count < array.length. The length of the array is the number of lements it contains - 4 - so stopping at "less than 4" means the count variable never exceeds three which allows for the fact that rray elements are indexed from zero. The four elements are numbered 0, 1, 2, & 3 (four elements) so ensuring count doesn't exceed 3 prevents errors.

I hope that helps you out!

Steve.