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.

Timothy Kaye
2,765 PointsSimple 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

Alexander Davison
65,456 PointsAha! 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!
Timothy Kaye
2,765 PointsTimothy Kaye
2,765 PointsGreat, many thanks Alexander! Writing it out as per below makes sense now.
Alexander Davison
65,456 PointsAlexander Davison
65,456 PointsExactly! That's how it works.