Kot Lin For Loop
Kot Lin For Loop
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
for Loop
When we know how many times we want a section of code to repeat, we often use a for loop.
A for loop starts with the for keyword and is followed by a statement that defines a loop variable
followed by identifying an iterator:
for(i in 1..4) {
println("I am in a loop!")
}
An iterator is an object that allows us to step through and access every individual element in a
collection of values. In most cases, the iterators we use in for loops are ranges and collections. In
this example, the range has 4 elements so the for loop repeats 4 times:
I am in a loop!
I am in a loop!
I am in a loop!
I am in a loop!
It is important to note that the loop variable only exists within the loop’s code block. Trying to
access the loop variable outside the for loop will result in an error.
Here is an example of using the loop variable within the loop body:
for (i in 1..4) {
println("i = $i")
}
While the above example uses literal numbers 1..4 to define the range, we can also use variables
to define the boundaries of our loop’s range, giving us more dynamic control over our loop’s
iteration:
i = 1
i = 2
i = 3
i = 4
Instructions
1.
Create a for loop that outputs "Hello, Codey!" five times.
Hint
With i as the loop variable and 1..5 as the iterator, create a for loop with println("Hello,
Codey!") as the loop body.
Now instead of just outputting text, it’s time to use the loop variable i in the loop body.
Add another println() with a string template directly below the first println() so the loop
creates the following output:
Hello, ilias!
i = 1
Hello, ilias!
i = 2
Hello, ilias!
i = 3
Hello, ilias!
i = 4
Hello, ilias!
i = 5
Checkpoint 3 Passed
Hint
Add a println() statement to the loop body with the string template "i = $i".
Concept Review
Helloilias.kt
fun main() {
for(i in 1..5){
println("Hello, ilias!")
println("i = $i")
Ouput:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Controlling the Iteration
Sometimes we want to count backwards, or count by 2s, or both! Using certain functions
alongside or instead of the normal range operator (..) can enhance the iterative abilities of
our for loops. The functions downTo, until and step give us more control of a range and therefore
more control of our loops.
The downTo function simply creates a reverse order group of values, where the starting boundary
is greater than the ending boundary. To accomplish this, replace the range operator (..)
with downTo:
for (i in 4 downTo 1) {
println("i = $i")
}
We can see in the output that the first number in i is 4 and the last is 1:
i = 4
i = 3
i = 2
i = 1
The until function creates an ascending range, just like the (..) operator, but excludes the upper
boundary:
for (i in 1 until 4) {
println("i = $i")
}
The upper boundary, 4, is not included in the output:
i = 1
i = 2
i = 3
Up until now, each of these functions, including the range operator (..), have counted up or
down by one. The step function specifies the amount these functions count by:
i = 1
i = 3
i = 5
i = 7
Instructions
1.
Let’s look at how we can change the behavior of ranges in for loops by implementing a loop that
counts backwards.
Hint
Create a for loop with i as the loop variable and 10 downTo 1 as the iterator. The loop body
should have a println() that outputs "i = $i".
Hint
Create a for loop with j as the loop variable and 1 until 10 as the iterator. The loop body
has println() that outputs "j = $j".
Run the code and you will see that the new loop does not output the iterator’s upper boundary 10.
Counting up by 2 from 1 does not include 10.
Checkpoint 4 Passed
Hint
Create a for loop with k as the loop variable and 1..10 step 2 as the iterator. The loop body
has println() that outputs "k = $k".
ranges.kt
fun main() {
for (i in 10 downTo 1) {
println("i = $i")
println("j = $j")
println("k = $k")
Output:
LOOPS
Iterating Through Collections
Instead of using a range, we can use the structure of a collection as an iterator.
A for loop will iterate through each of the collection’s elements with the loop
variable holding the value of the current element. We will focus on lists and
sets in this exercise and maps in the next one.
I have apples.
I have oranges.
I have bananas.
When we first learned about lists and sets in the collections lesson, we
discussed their commonality as well as their differences. An additional
similarity is that the syntax for iterating through a list and a set is the same.
Instructions
1.
Now you’ll use collections as iterators. To start, implement a for loop using the
list mySchedule. The loop should contain:
Hint
Create a for loop with task as the loop variable and mySchedule as the iterator.
The loop body should use println() to output the loop variable.
Hint
Destructure the loop variables taskIndex and task and
use myTasks.withIndex() as the iterator. The loop body should use println() to
output the string template "$taskIndex: $task".
fun main() {
val mySchedule = listOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
val myTasks = setOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
println("-- mySchedule Output --")
Soluations:
fun main() {
val mySchedule = listOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
val myTasks = setOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
println(task)
println("$taskIndex: $task")
}
Output:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Iterating Through Maps
Unlike a list or a set, a map is a collection of entries. When using a map as a for loop iterator, we
can iterate through each entry of the map or through just the keys, or just the values.
When iterating through a map, the loop variable will hold one entry per iteration. The entry’s key
and value can be accessed using the properties, key and value:
We can also access the key and value of each entry by destructuring using two loop variables in
parentheses. The first variable is the entry’s key and the second is the value:
println("KEYS")
for (itemName in myClothes.keys) {
println(itemName)
}
println("\nVALUES")
for (itemCount in myClothes.values) {
println(itemCount)
}
Here is the output:
KEYS
Shirts
Pairs of Pants
Jackets
VALUES
7
4
2
Instructions
1.
The map favoriteColors holds the names of people and their favorite colors. The keys of the
map are the people’s names and the values of the map are their favorite colors. Start by iterating
through the map favoriteColors to access each entry and output its key and value.
Be sure to use curly brackets in the string template when accessing the attributes of the entry in
the loop variable.
Checkpoint 2 Passed
Hint
Create a for loop with favoriteEntry as the loop variable and favoriteColors as the iterator. The
loop body should use println() to output the string template "${favoriteEntry.key}: $
{favoriteEntry.value}".
Hint
Create a second for loop with color as the loop variable and favoriteColors.values as the
iterator. The loop body should use println() to output the loop variable.
println("${favoriteEntry.key}: ${favoriteEntry.value}")
println(color)
}
LOOPS
while Loop
When repeating code we may not have a range or defined collection to dictate the number of
loops we need to execute. In this case, we can rely on a while loop which repeats code as long as
a specified condition is true. If we revisit the animation in the first exercise, we can see that
Codey uses a while loop to hike until time is no longer less than 17.
A while loop is similar to an if expression because it tests a condition and when the condition
is true a body of code is executed. The main difference is the while loop will complete the body
of code, check the condition, and repeat the code if the condition is still true. If the condition
is false, the while loop is done and the program moves on:
I am a teenager. // myAge is 16
I am a teenager. // myAge is 17
I am a teenager. // myAge is 18
I am a teenager. // myAge is 19
I am not a teenager. // myAge is 20
If myAge wasn’t incremented inside the loop body the loop condition would always be true and
repeat forever. This is known as an infinite loop. Infinite loops lead to application crashes or
other unwanted behavior so it is important that they are avoided.
When a while loop condition never evaluates to true, the entire block of code is skipped:
1.
Create a while loop that:
Hint
Create a while loop with the condition counter < 5. The loop body should contain println() to
output the value of counter as well as increment counter using the ++ operator.
while (conditionIsTrue) {
println(counterVariable)
counterVariable++
}
2.
A while loop condition can also check the elements of a collection. You’ll use another counter
variable, index, to access the collection’s elements.
When you’re done, you’ll see that the while loop exits once the element “6th” is the current one.
Hint
Create a while loop with the condition myFeelings[index] != "happy". The loop body should
use println() to output the value of myFeelings[index] as well as increment index using the +
+ operator.
fun main() {
var counter = 0
var index = 0
val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")
While.kt
fun main() {
var counter = 0
var index = 0
val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")
println(counter)
counter +=1
println(schoolGrades[index])
index++
Output:
LOOPS
do..while Loop
A do..while loop is just like a while loop except the looping condition is checked at the end of the
loop body. This is known as an exit-condition loop and means the code in the body will execute
at least once:
do {
print("I loop once!")
} while(myCondition)
This example shows that even though we have a false condition our loop will still run the loop
body once:
I loop once!!!!
One reason we would use a do..while loop is when our loop condition initialization and update
commands are the same. Using psuedocode we can compare a while loop with a do..while loop
using how someone might decide to go outside:
Is it sunny outside?
while ( not sunny ) {
Is it sunny outside?
Stay inside.
}
Go outside!
The while loop example has a line before the loop to check if it is sunny outside. The loop is
entered if it is not sunny and then repeatedly checks if it is sunny outside. When it is sunny, the
loop exits and it’s time to go outside:
do {
Is it sunny outside?
Stay inside.
} while ( not sunny )
Go outside!
The do..while loop enters the loop and starts by checking if isSunny is true. The loop body
repeats if the isSunny is false.
The extra check prior to the loop is unnecessary since it is performed inside the loop anyway. If
we have to look outside to get our initial loop condition and to update our loop condition, we
might as well have that be the loop body and check the condition at the end.
This difference may seem subtle, but if this loop is executed hundreds or thousands of times a
second, removing the one line of code using a do..while loop may save time.
Instructions
1.
We’ll implement a do..while loop that performs a Celsius to Fahrenheit temperature conversion.
First, construct a do..while loop that checks if fahr does not equal 212.0. Inside the loop body:
Hint
Implement a do..while loop with the loop condition, celsiusTemps[counter] != 212.0. Inside the
loop body, copy the 2 lines of code in the instructions and increment the index variable using
the ++ operator.
do {
fahr = celsiusTemps[counter] * fahr_ratio + 32
println(fahr)
listIndex++
} while (conditionIsTrue)
fahr = celsiusTemps[counter] * fahr_ratio + 32 is the conversion equation from Celsius to
Fahrenheit: FahrenheitTemp = (CelsiusTemp * 9/5) + 32.
fun main() {
var index = 0
do {
println("${celsiusTemps[index]}C = ${fahr}F")
index ++
} while (fahr != 212.0)
}
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Nested Loops
Loops inside loops, oh my! A nested loop represents one loop placed inside the body of another
loop which results in a higher dimensions of iterations. This strategy is most often used when
we’d like to compare the contents of two different collections/iterators.
Below is an example of nested loops. The outer loop iterates through the range 1..2 and the inner
loop iterates through the range 'A'..'C':
for (i in 1..2) {
for (j in 'A'..'C') {
println("Outer loop: $i - Inner loop: $j")
}
}
It’s important to understand that for every iteration in the outer loop, the inner loop will run
through all of its own iterations.
In the example above, the inner loop iterates 3 times for each of the outer loop’s 2 iterations.
Therefore, the println() statement is run 6 times:
Instructions
1.
You’ll be building a grid of rows and columns much like the ones that exist in Google and Excel
sheets using nested loops. First start with a single loop.
Hint
Create a for loop with i as the loop variable and 1..6 as the iterator. The loop body should be
empty.
The empty space at the end of the String template is used to create a gap between columns which
helps us visualize what is happening in the code.
Checkpoint 3 Passed
Hint
Create a for loop inside the first loop, with j as the loop variable and 'A'..'F' as the iterator.
The loop body should have a print() statement that outputs this string template "$j$i ".
Outside of the inner loop but still inside of the outer loop:
add an empty println() statement.
When you run the code you can now see that each inner loop iteration outputs a column, while
each outer loop iteration creates a new row.
Checkpoint 4 Passed
Hint
Add a blank println() statement to the end of the outer loop. The println() will create a new
row in the output.
for(outerLoopVar in outerIterator) {
for(innerLoopVar in innerIterator) {
print("$innerLoopVar$outerLoopVar")
}
println()
}
fun main() {
for (i in 1..6) {
for (j in 'A'..'F') {
print("$j$i ")
println()