For
You can use for loop on anything that is iterable and or anything has iterator()
function.
- Line 2 — we created a list using our data class
ThePillars
- Line 8 — we iterate throughout the list, for every element
i
in the list ofthePillars
. - Line 9 — since we’re referencing the data class
ThePillars
, we can get its parameterspillar
andname
- Line 13 — is the same as Line 8–11, but we used
forEach
function instead and theit
to referencethePillars
. - Line 18 — we can also use range using the
..
operator. Note that therange is inclusive
meaning it includes the start and the endpoint. - Line 22 — if we want a descending range, we can also use the
downTo
keyword.
Other useful operators and keywords:
While
- Line 2 — we’ve changed our list to
arrayListOf
to make it mutable - Line 9 — we added a new list of pillars
- Line 13 — we declared a counter
- Line 14 — here’s how to declare a while loop. Inside the parenthesis
()
you must declare a conditional statement - Line 15 & 16 — while our conditional statement doesn’t return true, the
count
variable will continue to increment and will also continue to add an item ofnewListOfPillars
tothePillars
list.
Do While
- The only difference between
while
anddo while
is that thedo while
will always first execute the code (inside the {})
before evaluating the condition inwhile()
.
Continue & Break
continue
keyword skips to the next iteration of the innermost containing loopbreak
keyword stops the loop
We’ll talk more about this when we discuss labels
Thanks! :D