Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.