0% found this document useful (0 votes)
72 views33 pages

Kot Lin For Loop

The document discusses using for loops to iterate through collections in Kotlin. It provides examples of using a list and set as iterators in a for loop. The loop variable will take on the value of each element in the collection. It also demonstrates using the indices property or withIndex() function to access both the element and its index during each iteration.

Uploaded by

ilias ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views33 pages

Kot Lin For Loop

The document discusses using for loops to iterate through collections in Kotlin. It provides examples of using a list and set as iterators in a for loop. The loop variable will take on the value of each element in the collection. It also demonstrates using the indices property or withIndex() function to access both the element and its index during each iteration.

Uploaded by

ilias ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

My Home

Course Menu
Workspace restored.
Get Unstuck
Tools

Loops: for Loop

Narrative and Instructions

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!")
}

 for isa keyword used to declare a for loop.


 We define i as the loop variable. This variable holds the current iteration value and can
be used within the loop body.
 The in keyword is between the variable definition and the iterator.
 The range 1..4 is the for loop iterator.

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:

var num = 4


for (i in 1..num) {
  println("i = $i")
}
Both of the code snippets produce the same final output:

i = 1
i = 2
i = 3
i = 4

Instructions

1.
Create a for loop that outputs "Hello, Codey!" five times.

Make sure to use:

 i asthe loop variable.


 The range 1 through 5 as the iterator.
 a println() in the loop body.
Checkpoint 2 Passed

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.

Use the following syntax:

for (loopVariable in iterator) {


  println("Some Text")
}
2.
Great job on setting up your first Kotlin for loop!

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".

println("String with $loopVariable")

Concept Review

Helloilias.kt

fun main() {

// Write your code below

for(i in 1..5){

println("Hello, ilias!")

println("i = $i")

Ouput:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Loops: Controlling the Iteration

Narrative and Instructions

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:

for (i in 1..8 step 2) {


  println("i = $i")
}
The loop variable i now increases by 2 for every iteration. The last number output is 7, since 2
steps up from that is 9 which is outside the defined range, 1..8:

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.

Create a for loop that contains:

 i as the loop variable.


 an iterator that starts at 10 and ends at 1.
 a println() statement in the loop body with the string template "i= $i".
Checkpoint 2 Passed

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".

Use the following syntax:

for (loopVariable in highVal downTo lowVal) {


  println("$loopVariable")
}
2.
Below the first loop, implement a for loop that counts up but stops just before the upper
boundary of the range. Make sure it contains:

 j as the loop variable.


 the range 1 up to but not including 10 as the iterator.
 a println() statement in the loop body with string template "j = $j".
Checkpoint 3 Passed

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".

Use the following syntax:

for (loopVariable in lowVal until highVal) {


  println("$loopVariable")
}
3.
Finally, implement a for loop that iterates over a range in steps greater than 1. Make sure it
contains:

 k as the loop variable.


 a range 1 through 10 as the iterator that counts up by 2.
 a println() statement in the loop body with string template "k = $k".

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".

Use the following syntax:

for (loopVariable in lowVal..highVal step stepVal) {


  println("$loopVariable")
}

ranges.kt

fun main() {

println("-- 1st for loop output --")

// Write your code below

for (i in 10 downTo 1) {

println("i = $i")

println("\n-- 2nd for loop output --")

// Write your code below


for (j in 1 until 10) {

println("j = $j")

println("\n-- 3rd for loop output --")

// Write your code below

for (k in 1..10 step 2) {

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.

val fruitList = listOf("apples", "oranges", "bananas")

for (fruit in fruitList) {


  println("I have $fruit.")
}
In this example, we declare fruit as the loop variable and use fruitList as the
iterator. Each iteration of the loop will set fruit to the value of the current
element of fruitList. Therefore, the number of elements contained
in fruitList determines the number of times println("I have $fruit.") is
executed:

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.

When iterating through a collection, it is often useful to know what element


number, or iteration, we are at. To iterate through the indices of a collection
you can use its indices property:

val fruitSet = setOf("apples", "oranges", "bananas")

for (setIndex in fruitSet.indices) {


  println("Index = $setIndex")
}
Here we see the indices of fruitSet output. Remember that the first index of a
list or a set is always 0:
Index = 0
Index = 1
Index = 2
We can also get the index AND the iterator element using the
collection’s withIndex() function. In this case we need to destructure the loop
variable declaration by declaring two loop variables and enclosing them in
parentheses:

val fruitList = listOf("apples", "oranges", "bananas")

for ((listIndex, fruit) in fruitList.withIndex()) {


  println("$listIndex is the index of the element $fruit")
}
Using withIndex() and destructuring, we are able to access both the index and
the element of fruitList:

0 is the index of the element apples


1 is the index of the element oranges
2 is the index of the element bananas

Instructions

1.
Now you’ll use collections as iterators. To start, implement a for loop using the
list mySchedule. The loop should contain:

 task as the loop variable.


 the list mySchedule as the iterator.
 a println() statement in the loop body that outputs the loop
variable.

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.

Use the following syntax:


for (loopVariable in iterator) {
  println(loopVariable)
}
2.
Great, now look at the set myTasks which is declared with the same elements as
the list. We know that myTasks will have fewer elements since some of them are
repeated and will only be represented once in the set. Let’s confirm this by
printing out the indices AND the elements of the set.

Create another for loop that contains:

 taskIndex and task as destructured loop variables. Be sure to


separate them with a comma and enclose them in parentheses.
 myTasks using the withIndex() function as the iterator.
 a println() statement in the loop body with the
output taskIndex and task separated by a colon (:). Example
output: 0: Eat Breakfast

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".

The final code should look similar to the example below:

for ((indexVar, elementVar) in listVar.withIndex) {


  println("$indexVar: $elementVar")
}

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 --")

// Write your code below

println("\n-- myTasks Output --")

// Write your code below

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("-- mySchedule Output --")

// Write your code below

for (task in mySchedule) {

println(task)

println("\n-- myTasks Output --")

// Write your code below

for ((taskIndex, task) in myTasks.withIndex()) {

println("$taskIndex: $task")

}
Output:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Loops: Iterating Through Maps

Narrative and Instructions

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:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets"


to 2)

for (itemEntry in myClothes) {


  println("I have ${itemEntry.value} ${itemEntry.key}")
}
Notice that in order to access the attributes in a String template, we surround the loop variable
and the attribute in curly brackets.

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:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets"


to 2)

for ((itemName, itemCount) in myClothes) {


  println("I have $itemCount $itemName")
}
Both examples have the same output:
I have 7 Shirts
I have 4 Pairs of Pants
I have 2 Jackets
Lastly, we can iterate through just a map’s keys or values. A map has the
properties keys and values which can each be used as an iterator:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets"


to 2)

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.

Implement a for loop that contains:

 favoriteEntry as the loop variable


 favoriteColors as the iterator
 a println() statement in the loop body that outputs the key and value of each
entry separated by a colon. Example output, Jesse: Violet

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}".

Use the following syntax:

for (loopVariable in iterator) {


  println("${loopVariable.key}: ${loopVariable.value}")
}
2.
Nice work. Now you’re going to create a loop that iterates through just the map’s values.

Create another for loop that contains:

 color as the loop variable


 the values attribute of favoriteColors as the iterator.
 a println() statement in the loop body that outputs the value of each entry.
Checkpoint 3 Passed

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.

Use the following syntax:

for (loopVariable in iterator) {


  println(loopVariable)
}
fun main() {

val favoriteColors = mapOf("Jesse" to "Violet", "Megan" to "Red", "Tamala" to "Blue", "Jordan" to


"Pink")

println("\n-- Key: Value Output----")

// Write your code below

for (favoriteEntry in favoriteColors) {

println("${favoriteEntry.key}: ${favoriteEntry.value}")

println("\n-- Only Values Output-----")

// Write your code below

for (color in favoriteColors.values) {

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:

var myAge = 16

while (myAge < 20) {


  println("I am a teenager.")
  myAge += 1
}
println ("I am not a teenager.")
In this example the while loop condition myAge < 20 initially evaluates to true. The loop body is
executed which outputs some text and myAge is incremented. The loop repeats until myAge equals
20 at which point the loop exits and continues running code outside the loop:

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:

var myAge = 11

while (myAge > 12 && myAge < 20) {


  println("I am a teenager.")
  myAge += 1
}
println ("I am not a teenager.")
Since we’ve set the value of myAge to 11 and the condition will only be true once the value is
between 12 and 20, the code block is skipped and the final println() gets executed:

I am not a teenager. // myAge is 11


Instructions

1.
Create a while loop that:

 repeats as long as the variable counter is less than 5.


 uses println() in the loop body to output the variable counter.
 increments the variable counter by 1 in the loop body.

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.

Use the following syntax:

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.

Implement a second while loop that:

 has the condition, schoolGrades[index] != "6th".


 uses println() in the loop body to output the current element value
of schoolGrades.
 increments the variable index by 1 in the loop body.

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.

Use the following syntax:

while (listName[indexValue] != "testString") {


  println(listName[indexValue])
  indexValue++
}

fun main() {
var counter = 0

var index = 0

val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")

println("-- counter Output --")

// Write your code below

println("\n-- Elementary School Grades --")

// Write your code below

While.kt

fun main() {

var counter = 0

var index = 0

val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")

println("-- counter Output --")

// Write your code below

while (counter < 5) {

println(counter)

counter +=1

println("\n-- Elementary School Grades --")


// Write your code below

while (schoolGrades[index] != "6th") {

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:

val myCondition = false

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:

 paste the following 2 lines of code.

fahr = celsiusTemps[index] * fahr_ratio + 32.0


println("${celsiusTemps[index]}C = ${fahr}F")

 increment the value of index.


Checkpoint 2 Passed

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.

Use the following syntax:

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

val celsiusTemps = listOf(0.0, 87.0, 16.0, 33.0, 100.0, 65.0)

val fahr_ratio = 1.8

var fahr: Double

println("-- Celsius to Fahrenheit --")

// Write your code below

do {

fahr = celsiusTemps[index] * fahr_ratio + 32.0

println("${celsiusTemps[index]}C = ${fahr}F")

index ++
} while (fahr != 212.0)

}
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Loops: Nes ted Loops

Narrative and Instructions

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:

Outer loop: 1 - Inner loop: A


Outer loop: 1 - Inner loop: B
Outer loop: 1 - Inner loop: C
Outer loop: 2 - Inner loop: A
Outer loop: 2 - Inner loop: B
Outer loop: 2 - Inner loop: C
When beginning with nested loops they may seem difficult to work with, but they make
advanced applications easy to implement.

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.

Create a for loop that contains:

 i as the loop variable.


 a range of 1 through 6 as the iterator.
Checkpoint 2 Passed

Hint
Create a for loop with i as the loop variable and 1..6 as the iterator. The loop body should be
empty.

Use the following syntax:

for (loopVariable in iterator) {


  // code goes here
}
2.
Now you will implement another loop inside the first one.

Inside the first loop body, create a for loop that contains:

 j as the loop variable.


 a range of 'A' through 'F' as the iterator.
 a print() statement that outputs "$j$i ".

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 ".

Use the following syntax:

for (outerLoopVar in outerIterator) {


  for (innerLoopVar in innerIterator) {
    print("$innerLoopVar$outerLoopVar")
  }
}
3.
There is now a single line of each loop variable concatenated to each other. The last step will
show off the dimensional nature of nested loops.

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.

Use the following syntax:

for(outerLoopVar in outerIterator) {
  for(innerLoopVar in innerIterator) {
    print("$innerLoopVar$outerLoopVar")
  }
  println()
}

fun main() {

// Write your code below

for (i in 1..6) {

for (j in 'A'..'F') {

print("$j$i ")

println()

You might also like