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

Timothy Kaye
Timothy Kaye
2,765 Points

Simple Loop question.

var total = 10
for i in 0..<5 {
total += i
}
print(total)

This is a very simple loop, however, I cannot wrap my head around how the loop returns a total value of 20 when printed to the compiler. Can someone talk me through the steps that the compiler is taking to achieve 20?

Many thanks!

1 Answer

Aha! Sneaky. It took me a while to see why it returns "20". Here's an example first:

for i in 0 ..< 5 {
   print(i)
}

This will print:

0 1 2 3 4

This is because the variable "i" keeps incrementing, or adding one on itself. So when you add "i" to total, it will add on 1, then 2, then 3, etc.

Hope that makes sense! :dizzy:

Timothy Kaye
Timothy Kaye
2,765 Points

Great, many thanks Alexander! Writing it out as per below makes sense now.

1   2   3   4   5   // number of passes

0   1   2   3   4   // number passed

10  11  13  16  20  // new total number

//  1st pass = 10 (initial value)
//  2nd pass = 10 (initial value) + 1 (number passed) = 11 (new total)
//  3rd pass = 11 (new total) + 2 (number passed) = 13 (new total)
//  4th pass = 13 (new total) + 3 (number passed) = 16 (new total)
//  5th pass = 16 (new total) + 4 (number passed) = 20 (new total)

//  var total = 20 (new total)

Exactly! That's how it works.