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 trialTimothy 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,469 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,469 PointsAlexander Davison
65,469 PointsExactly! That's how it works.