[go: up one dir, main page]

0% found this document useful (0 votes)
470 views119 pages

KotLin For Loop

KotLin for Loop

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)
470 views119 pages

KotLin For Loop

KotLin for Loop

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/ 119

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

}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Loops: Jump Expressions

Narrative and Instructions

Learn
LOOPS
Jump Expressions
The jump expressions, break and continue, are used to change the standard loop behavior by
exiting a loop early or skipping a single repetition.

The break expression is used to exit the loop at a particular iteration:

val myNumbers = listOf(4, 8, 2, 9, 12, 7, 16, 10, 3)


for (num in myNumbers) {
  if (num > 9) {
    break
  }
  println(num)
}
In this example:

 the for loop iterates through the list of Ints.


 each iteration the current number, num, is tested to see if it is greater than 9.
 if false, the number is output.
 if true, the break expression exits the loop.

We can see the below output stops before printing the number 12:

Output
4
8
2
9
The continue expression will skip the current execution of the loop body, but the loop will keep
going if there are iterations left. If the continue expression gets executed, any code left in the
current iteration will be skipped:

val myNumbers = listOf(4, 8, 2, 9, 12, 7, 16, 10, 3)


for (num in myNumbers) {
  if (num > 9) {
    continue
  }
  println(num)
}
This example is the same as the last but we replaced the break with continue. The below output
skips all values of num greater than 9, while printing out the rest of numbers:

Output
4
8
2
9
7
3
The first example outputs the elements in myNumbers until you reach one greater than 9. The
second example outputs all elements in myNumbers except those that are greater than 9.

Since jump expression are usually contained inside if expressions, they gives us the ability to
add a condition to exit a for loop or using another condition to exit a while loop.

Don’t worry if this all doesn’t stick right away; keep practicing with each jump expression and
you’ll quickly get the hang of how and when each one is used.

Instructions

1.
The code on the right is “looking” for something in different rooms of a house. Thankfully we
know that the item being searched for is in the "Living Room".

Your job is to instruct the for loop to stop looking once it reaches "Living Room":

 After the print("$room: ") statement add an if expression that tests if the loop


variable room is equal to "Living Room".
 Inside the if block use a println() statement to output the String, "Found It!"
 Inside the if block add the appropriate jump expression that will stop the
iteration.

Hint
In the first for loop, add an if expression with the condition room == "Living Room". Inside
the if expression, output “Found It!” using println(). Inside the if statement add
a break expression.

Use the following syntax:

for(room in rooms) {
  print("Searching $room: ")
  // Write your code below
  if (condition) {
    println(message)
    break
  }
  println("Found Nothing")
}
2.
Good work! We also come across situations where we may want to skip a loop iteration. The
second for loop in the editor causes a division by zero error. This is undesirable, and we need to
add code to the body of the for loop to avoid this.

 At the start of the loop add an if expression that tests if number is 0.


 Inside the if expression add a continue expression.

Hint
In the second for loop, add an if expression with the condition number == 0. Inside
the if expression add a continue expression. When you run the code you should see no more
error and the output from each iteration EXCEPT when number is 0.

Use the following syntax:

for(number in 12 downTo -12 step 4) {


  // Write your code below
  if (condition) {
    continue  
  }
  println("120/$number = ${120/number}")
}

fun main() {

val rooms = listOf("Kitchen", "Living Room", "Basement", "Bathroom")

println("-- Room Search --")


for (room in rooms) {

print("$room: ")

// Write your code below

println("Found Nothing.")

println("\n-- Divide By Zero --")

for (number in 12 downTo -12 step 4) {

// Write your code below

println("120/number = ${120/number}")

fun main() {

val rooms = listOf("Kitchen", "Living Room", "Basement", "Bathroom")

println("-- Room Search --")

for (room in rooms) {

print("$room: ")

// Write your code below

if (room == "Living Room") {

println("Found It!")

break

}
println("Found Nothing.")

println("\n-- Divide By Zero --")

for (number in 12 downTo -12 step 4) {

// Write your code below

if (number == 0) {

continue

println("120/number = ${120/number}")

}
Learn
LOOPS
Labeled Jump Expressions
“How would we use jump expressions inside nested loops?” Good question! The answer
is labeled jump expressions. By adding a label to the outer loop of nested loops, we can execute a
jump expression from the inner loop and have it act on the labeled outer loop.

First we need to give a name to our label. In the following example we choose the name rps. The
outer loop is marked using our label rps followed by the @ symbol:

val game = listOf("Rock", "Paper", "Scissor")

rps@ for (p1 in game) {


  for (p2 in game) {
    if (p1 == "Paper") {
      break@rps
    }
    println("$p1 vs. $p2")
  }
}
The inner loop has an if expression that contains a break expression with @rps appended. When
the condition, p1 == "Paper" is true, break@rps executes and exits the outer loop:

Rock vs. Rock


Rock vs. Paper
Rock vs. Scissor
Now let’s look at what happens in our example when we change the break expression to
a continue:

val game = listOf("Rock", "Paper", "Scissor")

rps@ for (p1 in game) {


  for (p2 in game) {
    if (p1 == "Paper") {
      continue@rps
    }
    println("$p1 vs. $p2")
  }
}
What we see now is the outer loop skips an iteration when p1 == "Paper" but resumes with the
final iteration when p1 is equal to “Scissor”:

Rock vs. Rock


Rock vs. Paper
Rock vs. Scissor
Scissor vs. Rock
Scissor vs. Paper
Scissor vs. Scissor
Labeled jump expressions give us more control over nested loops to help us achieve the desired
behavior from our code. Using them can be tricky, but once understood they can be very
powerful.

Instructions

1.
Recall the 6x6 grid with “A1” to “F6”” cells from the previous exercise. We’ll take a closer look
at how we can manipulate the structure and output of this grid using labeled jump expressions.

First, add a label grid to the outer loop.


Checkpoint 2 Passed

Hint
Add the label grid to the outer loop.

Use the following syntax:

label@ for (i in 1..3) {


  for(j in 1..3) {
    print("$j$i ")
  }
}
2.
Add an if expression inside the inner loop, before the print("$j$i ") statement. Have the
condition test if the inner loop variable is equal to 'C'.
Checkpoint 3 Passed

Hint
Add an if expression with the condition j == 'C' at the top of the inner loop.

Use the following syntax.

label@ for (i in 1..3) {


  for(j in 1..3) {
    if (j == 'A') {
    }
    print("$j$i ")
  }
}
3.
Inside the if expression add a continue expression that jumps to the grid label.

Once you run the code you should see a single line of output. The outer loop numbers go
from 1 through 6, but the inner loop letters only go up through 'B'.
It is important to note that the println() statement at the end of the outer loop is also skipped.
The result is only one row is printed. This shows that a labeled continue will skip any code
proceeding it in the inner loop and at the end of the outer loop.
Checkpoint 4 Passed

Hint
Add a labeled continue expression with the label grid.

Use the following syntax:

label@ for (i in 1..3) {


  for(j in 1..3) {
    if (j == 'A') {
      continue@label
    }
    print("$j$i ")
  }
}

fun main() {

// Write your code below

grid@ for (i in 1..6) {

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

// Write your code below

if (j == 'C') {

continue@grid

print("$j$i ")

println()

}
https://github.com/Codecademy

https://github.com/Codecademy

https://github.com/Codecademy

https://github.com/Codecademy

https://github.com/Codecademy

https://github.com/iaahmed220/codecademy-projectshttps://github.com/iaahmed220/codecademy-
projects

https://github.com/iaahmed220/codecademy-projects

https://github.com/iaahmed220/codecademy-projects

https://github.com/Codecademy/learn-kotlin/blob/main/5-loops/Shapes.kt
fun
main(
) {
// Square Variables
val sqSide = 7
val sqChar1 = "X "
val sqChar2 = "O "
// Write your code below
for (i in 1..sqSide) {
for (j in 1..sqSide) {
if (i % 2 == 0 && j % 2 == 0 || i % 2 == 1 && j % 2 ==1) {
print(sqChar1)
} else {
print(sqChar2)
}
}
println()
}

// Triangle Variables
val triRows = 10
var triCount = 0
var triRowLen = triRows
val triChar1 = "/ "
val triChar2 = " "

// Write your code below


for (i in triRows downTo 1) {
while (triCount < triRowLen) {
triCount++
print(triChar1)
}
println()
triCount = 0
triRowLen--
}

triRowLen = triRows
for (i in triRows downTo 1) {
while (triCount < triRowLen) {
triCount++
if (triCount != 1 && triCount != triRowLen && i != triRows)
{
print(triChar2)
} else {
print(triChar1)
}
}
println()
triCount = 0
triRowLen--
}
}

 © 2021 GitHub, Inc.


My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Learn Kotlin: Shape Maker

Brief

Objective
LEARN KOTLIN
Shape Maker
How many output statements do you need to draw two-dimensional shapes? Using loops, the
answer to this question is 2. In this project, you will create a square and a triangle of any size
using nested loops with one print() statement and one println() statement.

We’ll create a basic square pattern using loop concepts we covered in the previous lesson. We’ll
even take it a step further by getting our program to output a checkerboard pattern.

Then, we’ll explore how nesting a while loop inside of a for loop can be used to create a triangle
pattern in the output terminal. This will give us a different perspective of nested loops and how
to control variables when using while loops.

Good luck with the project and have fun!

Tasks

14/14 Complete
Mark the tasks as complete by checking them off
Creating a Square Pattern
1.
In Shapes.kt, there are two groups of variables: one for making a square and one for making a
triangle.

The first group of variables will be used to draw a square using nested for loops:

 sqSide defines the length of the square’s side.


 sqChar1 and sqChar2 define the output characters used to create the square and checker
board.

sqChar1 and sqChar2 each represent one column and are each 3 characters long to account for the
space between rows.

Review the variables and move to the next task when ready.
Hint
Square Variable Group:

 val sqSide = 7 defines the side length and will create a square of 7 x 7 characters.
 val sqChar1 = "X " defines the output character String used to create the square.
 val sqChar2 = "O " defines the output character String used to help create the checker
board.

2.
Start your code under the first group of variables by creating a for loop with an iterator that starts
at 1 and goes through the value of sqSide. This will act as the outer loop of the code.

Put a blank println() in the loop body. This will create the rows of the square.
Stuck? Get a hint
3.
Now, let’s add an inner loop to output each column in a row.

Inside the outer for loop, create an inner for loop before the println() statement. Use the same
iterator as the outer loop.

Inside the inner loop body use a print() statement to output the value of sqChar1.
Hint
Follow this syntax to define the inner loop and character output:

for (outerLoopVar in 1..sideLen) {


  for (innerLoopVar in 1..sideLen) {
    print(stringVar)
  }
  println()
}
The output should resemble this:

X  X  X  X  X  X  X  
X  X  X  X  X  X  X  
X  X  X  X  X  X  X  
X  X  X  X  X  X  X  
X  X  X  X  X  X  X  
X  X  X  X  X  X  X  
X  X  X  X  X  X  X
Creating a Checker Board Pattern
4.
To create a checker board, we need to use the loop variables in an if expression to decide which
character to output.

In the inner loop, replace the print() statement with an if expression. The if expression should


output sqChar1 when both loop variables are even OR both loop variables are odd.

Otherwise, output sqChar2.
Hint
Use the modulus (%) operator to test if the loop variables are both even OR both odd.

Even Condition:

outerLoopVar % 2 == 0 && innerLoopVar % 2 == 0


Odd Condition:

outerLoopVar % 2 == 1 && innerLoopVar % 2 == 1


The if expression can test the conditions together using the OR (||) conditional operator:

if ((even condition) || (odd condition) ) {


  print(stringVar1)
} else {
  print(stringVar2)
}
Alternatively, the if expression can test the conditions separately using an else if expression:

if ( EVEN condition) {
  print(stringVar1)
} else if (ODD Condition) {
  print(stringVar1)
} else {
  print(stringVar2)
}
The output should resemble:

X  O  X  O  X  O  X  
O  X  O  X  O  X  O  
X  O  X  O  X  O  X  
O  X  O  X  O  X  O  
X  O  X  O  X  O  X  
O  X  O  X  O  X  O  
X  O  X  O  X  O  X
Creating a Triangle Pattern
5.
Now we’ll move on to creating a triangle pattern.

Take a look at the next group of variables that will be used to draw a triangle:

 triRows defines the triangle rows.


 triCount is a counter for the inner while loop.
 triRowLen keeps track of each row length.

There are also 2 more String variables to use for output: triChar1 and triChar2.

Review the variables and move to the next task when ready.
Hint
Triangle Variable Group:

 val triRows = 10 defines the number of rows in the triangle.


 var triCount = 0 initializesthe counter used in the inner while loop
 var triRowLen = triRows initializes the current row length to the value of triRows
 val triChar1 = "/ " defines the output character String used to create the triangle.
 val triChar2 = " " defines the blank output character String used to help create the
triangle outline.

6.
Start off the code for the triangle pattern by using a for loop that counts down from triRows to 1.
This will act as the outer loop of the code.

Inside the loop body insert a blank println().


Hint
Follow this syntax to define the outer loop and new row output:

for (outerLoopVar in numRows downTo 1) {


  println()
}
7.
Inside the for loop, create a while loop before the println() statement. The while loop should
repeat when triCount is less than triRowLen.

Increment triCount inside the loop. Make sure to run your code only after you’ve added the
increment, otherwise, you’ll run into an infinite loop. If you have, you might need to refresh the
web page.
Hint
Follow this syntax to define the inner loop and triCount incrementation:
for (outerLoopVar in numRows downTo 1) {
  while (countVar < rowVar) {
    countVar++
  }
  println()
}
8.
Add a print() statement to the while loop body directly below the increment to output triChar1.

Run the code and look at the output. Do you see a single line of characters? Can you figure out
why your output is the way it is?
Hint
Follow this syntax to include the print() statement inside the inner loop:

for (outerLoopVar in numRows downTo 1) {


  while (countVar < rowVar) {
    countVar++
    print(stringVar)
  }
  println()
}
9.
The while loop is responsible for outputting triChar1. There is a possibility that the
condition triCount < triRowLen is true only for the first outer loop iteration causing the inner
loop to only output a single line.

To prevent this, outside the while loop (but inside the for loop), set triCount to its initial value, 0.
This will ensure that at the start of each iteration of the for loop, triCount is less
than triRowLen and the while loop body will execute.
Hint
Follow this syntax to reset the value of triCount to 0:

for (outerLoopVar in numRows downTo 1) {


  while (countVar < rowVar) {
    countVar++
    print(stringVar)
  }
  println()
  countVar = 0
}
10.
Run your code. Do you see a square? If so, why? The goal is to make a triangle!

To make our pattern look like a triangle, we need to adjust the length of each new row. To
accomplish this, decrement the value of triRowLen at the end of the for loop’s body.
Hint
Follow this syntax to decrement the value of triRowLen:

for (outerLoopVar in numRows  downTo 1) {


  while (countVar < rowVar) {
    countVar++
    print(stringVar)
  }
  println()
  countVar = 0

  // Decrement triRowLen


  rowVar--
}
The output should resemble:

/  /  /  /  /  /  /  /  /  /  
/  /  /  /  /  /  /  /  /  
/  /  /  /  /  /  /  /  
/  /  /  /  /  /  /  
/  /  /  /  /  /  
/  /  /  /  /  
/  /  /  /  
/  /  /  
/  /  
/
Creating a Triangle Outline Pattern
11.
We’re going to modify our triangle code to just output the triangle’s outline. Feel free to make a
copy of the code created in steps 6-10 if you want to keep the full triangle output.

If you copied the code to make a 2nd triangle, be sure to set the value
of triRowLen to triRows just prior to the newly copied code.

Confirm the output of a 2nd triangle and move to the next task to implement the triangle outline.
Hint
Reset the value of triRowLen with the following statement, triRowLen = triRows and copy your
previous code over to start the triangle outline:

rowVar = numRows  

for (outerLoopVar in numRows  downTo 1) {


  while (countVar < rowVar) {
    countVar++
    print(stringVar)
  }
  println()
  countVar = 0
  rowVar--
}
12.
To create a triangle border, we need to output a visible character at the triangle edges and blank
space everywhere else.

In the inner loop, replace the print() statement with an if expression. The if expression should


test if the output is not an edge. There are three conditions that must be true in order for a
character to not be an edge:

 The while loop counter is not equal to 1.


 The while loop counter is not equal to the current row length.
 The for loop variable is not equal to the total number of rows.

If all three conditions are true, then output triChar2. Otherwise, output triChar1


Hint
Create a condition that checks if your defined outer loop variable and triCount are not on an
“edge” of the triangle:

if (countVar != 1 && countVar != rowVar && outerLoopVar != numRows ) {


  print(stringVar2)
} else {
  print(stringVar1)
}
The output should resemble:

/  /  /  /  /  /  /  /  /  /  
/                       /  
/                    /  
/                 /  
/              /  
/           /  
/        /  
/     /  
/  /  
/  
Optional
13.
Great work on the project! Here are a couple more tasks you can work on if you want to keep
going.
 Change the values of sqChar1, sqChar2, triChar1 and triChar2 to see how they affects the
look of each shape.
 Use different conditions within the if expressions of the square shape to explore what
other patterns you can generate.
 In the triangle outline code, instead of using an else to output triChar1, use a continue in
the if block to skip the rest of the while loop code.

Hint
Optional task 1:

Here are some example values for the output characters:

val sqChar1 = "@  "


val sqChar2 = "&  "

val triChar1 = "_  "


val triChar2 = "-  "
Optional task 2

In the square code, you can change the condition of the if expression to:

if (outerLoopVar == innerLoopVar || outerLoopVar + innerLoopVar ==


sideLen + 1)
This will output an X pattern using sqChar1.

Optional task 3:

In the triangle outline code, remove the else statement and put continue at the end of
the if block:

if (countVar > 0 && countVar < rowVar && outerLoopVar != numRows ) {
  print(stringVar2)
  continue
}
print(stringVar1)
This accomplishes the triangle outline by printing triChar2 and skipping the output
of triChar1 when the condition is true. Otherwise the code will output triChar1.
14.
Sample Solutions:

 Shapes.kt

If you make something cool, share your work with us!


Hint
Tag @Codecademy on Twitter or make a Pull Request to the Learn Kotlin GitHub repo for a
chance be featured in the course.
FUNCTIONS
Creating and Calling a Function
In order to declare a function, we’ll need to understand the anatomy of a basic function.

A function header contains valuable information about a function including its name, arguments,
and its return type.

fun funcName(argName: Type): returnType {


Function Body
}

 The fun keyword is used to declare a function.


 The function name is used to call the function throughout the program.
 Inside the parentheses are arguments- pieces of data fed to the function.
 The return type declares the type of data the function will return; it is also optional to
include.
 Following the function header is the function’s body where instructions are contained.

We’ll cover arguments and return types later in this lesson. For now, we’ll focus our attention on
creating a basic function that outputs a value whenever we call it.

Let’s create a function called greeting() that prints "Hello friend!":

fun greeting() {
  println("Hello friend!")
}
A function will only execute when it is called or invoked. While the function greeting() will
exist outside the main() function, we will call greeting() within main() by writing the function’s
name followed by parentheses:

fun greeting() {
  println("Hello friend!")
}

fun main() {
  // Invoke the function
  greeting()
}
// Prints: Hello friend!
Anytime we call greeting(), "Hello, friend!" will be outputted to the terminal.

Instructions

1.
Create a function named smores() that outputs the following statements using println():

 "Roast a marshmallow."
 "Place marshmallow on a graham cracker."
 "Place chocolate on marshmallow."
 "Put a new graham cracker on chocolate."
 "Enjoy!"

Hint
To create a function, create a function header and body. The function header will contain
the fun keyword, the function name, a pair of empty parentheses (( and )) and curly brackets
({ and }) to hold the function body:

fun functionName() {
  println("Statement 1")
  println("Statement 2")
  println("Statement 3")
  println("Statement 4")
  println("Statement 5")
}
2.
Invoke smores() in the main() function.
Hint
Inside the main() function, write the name of the function followed by parentheses (( and )) to
invoke the function:

fun main() {
  functionName()
}
3.
Optional:

Call smores() again. Note how time is saved by calling a function instead of writing the
instructions again.
Hint
Using the smores() function, we can output the 5 println() statements using a single function
call.

// Write your code below


fun main() {

// Write more code below

// Write your code below

fun smores() {

println("Roast a marshmallow.")

println("Place marshmallow on a graham cracker.")

println("Place chocolate on marshmallow.")

println("Put a new graham cracker on chocolate.")

println("Enjoy!")

fun main() {

// Write more code below

smores()

}
FUNCTIONS
Arguments
Arguments are pieces of data we can feed to our functions in order to produce dynamic results.
We can include as many arguments as the function needs.

Think of the println() function. When we use it, we give it a single argument: a String value.
This value is then passed and outputted to the terminal.

To pass arguments into a function, we need to add parameters to our function header. Parameters
are the names given to data being passed into a function. For example:

fun calculateForce(mass: Int, acceleration: Int) {


  var force = mass * acceleration
  println("The force is $force Newtons.")
}
In the parentheses of the function header, we added two parameters: mass and acceleration.

 Each parameter is separated by a comma (,).


 The parameter starts with its name, followed by a colon (:), and then the parameter type.

The parameters can then be referenced within the function body like a variable. The value of
each parameter is determined by the arguments used when invoking the function:

calculateForce(5, 12)
When calculateForce() is called, the values 5 and 12 are passed as arguments into the function.
The value of the parameter mass will be 5 and the value of acceleration will be 12. Invoking the
function with these argument values will give us the following output:

The force of this object is 60 Newtons.


An important concept to understand with functions is scope. Scope dictates the environment in
which a variable can be accessed within a program. If we were to try and reference the variable
force anywhere in our program outside of the calculateForce() function, we would receive an
error because the variable only exists within that function.

Instructions

1.
Create a function called getSpeed() that accepts two Int arguments: distance and time.

Inside the function, create a variable called speed that is equal to the value of distance / time.

Use println() and a String template to output the following statement:

[speed] meters per second


Hint
To write a function that accepts arguments, place the argument’s name and type inside the
function header.

If we have a function that accepts an Int argument called num and a String argument named text,
our header would look like this:

fun functionName(num: Int, text: String) {


  ...
}
2.
Invoke the getSpeed() function inside main().

Set the argument value of distance to 10 and the value of time to 3.


Hint
When invoking a function with arguments, place the arguments in the order they appear in the
function header:

fun main() {
  functionName(argument1, argument2)
}

// Write your code below

fun getSpeed(distance: Int, time: Int) {

var speed = distance / time

println("$speed meters per second")

fun main() {

// Write more code below

getSpeed(10, 3)

}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Functions: Named and Default Arguments

Narrative and Instructions

Learn
FUNCTIONS
Named and Default Arguments
We can go further with arguments by naming them or setting default parameter values.

To improve the readability of our code, we can name our arguments when invoking the function.
For example, with our calculateForce() function, we can add the names of arguments to our
function call:

fun calculateForce(mass: Int, acceleration: Int) {


  var force = mass * acceleration
  println("The force is $force Newtons.")
}

fun main() {
  // Invoke the function with named arguments.
  calculateForce(acceleration = 12, mass = 5)
  // Prints: The force is 60 Newtons.
}
Note that by naming our arguments when we invoke a function, we do not need to place the
arguments in the same order as they appear in the function header.

Default arguments provide values to function arguments if none are given when the function is
called. To implement this, we add an assignment operator and a value after the argument in the
function header, like so:

fun greetCustomer(name: String = "Customer") {


  println("Hello, $name.")
}
In the greetCustomer() function, we set the default value of the argument name to "Customer".
If we invoke this function with a String value, that value will become the value of name; however,
if no argument is given, name will have a value of "Customer":

greetCustomer("Cynara") // Prints: Hello, Cynara.


greetCustomer() // Prints: Hello, Customer.

Instructions

1.
An online shop has a special coupon code to get 15% off a customer’s final purchase.

Create a function called getPrice() that accepts a Double type argument named price as well as


a String argument called couponCode that has a default value of "None".

Leave the body empty for now.


Hint
Make sure to give a default value of "None" to the argument couponCode. The function header
should look similar to the one below:

fun functionName(arg1: Int, arg2: String = "None") {


  ...
}
2.
Inside the function, declare a Double type variable called finalPrice.

Then, create an if/else expression.

 If the value of couponCode is "save15", set finalPrice to price * .85.


 In the else expression, set finalPrice to price.

Outside the conditional, use println() and a String template to output the following statement:

The total price is [finalPrice].


Hint
To declare a variable with a Double type, use the following syntax:

var variableName: Double


Make sure to create an if expression that checks if couponCode is equivalent to "coupon15". The
final print statement should be added outside of the conditionals, similar to the example below:

fun functionName(arg1: Double, arg2: String) { 


  var variableName: Double

  if (arg2 == "String value") {


    // Add code here
  } else {
    // Add code here
  }
  // Add print statement here
}
3.
Inside the main() function, invoke getPrice().

When invoking getPrice(), use named arguments to give price a value of 48.0 and couponCode a


value of "save15".
Hint
When invoking the function, name the arguments by prepending the value with the argument
name displayed in the function header and the assignment operator.

For example, if the function looked like this:

fun functionName(arg1: Int, arg2: String = "None") {


  ...
}
Then invoking the function with named arguments could look like this:

functionName(arg1 = 15, arg2 = "coupon12")


4.
Optional:

Invoke getPrice() for a second time. This time, only give the program a single argument: 48.0.

Observe what happens when no argument for couponCode is given.


Hint
Since we did not provide an argument, couponCode is given the default value of "None".

// Write your code below

fun getPrice(price: Double, couponCode: String = "None") {

var finalPrice: Double

if (couponCode == "save15") {

finalPrice = price * .85

} else {

finalPrice = price
}

println("The total price is $finalPrice.")

fun main() {

// Write more code below

getPrice(price = 48.0, couponCode = "save15")

}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Functions: Return Statements

Narrative and Instructions

Learn
FUNCTIONS
Return Statements
The functions in the previous exercises produced output via println() statements contained
within its code body; however, we also have the ability to return a value from a function.

A return statement returns a value from a function and passes it back to where the function was
invoked. This value can then be used throughout our program.

If we want a function to return a value, we must add the return type to the function header as
well as a return statement in the body. Take a look at the following example where we create a
function that takes in a list of Ints and returns an Int value:

fun listSum(myList: List<Int>): Int {


  var sum = 0
  // iterate through each value and add it to sum
  for (i in myList) {
    sum += i
  }
  // return statement
  return sum
}

 The return type describes the data type of the value being returned and is stated after the
parentheses and a colon : in the function header.
 The keyword return is used to declare a return statement. In this case, sum is the value
being returned.
 Any lines of code that exist after the return statement will not be executed.

Previously, we invoked functions by calling them on their own line of code; however, we can
also invoke a function and assign it to a variable for later use.
For example, we can set total to the return value of listSum() after sending it a list of Int values
(billsToPay):

var billsToPay = mutableListOf(44, 29, 104, 79)

// Set total to the return value of listSum().


var total = listSum(billsToPay)
println("Your bill total is $total dollars.")
This will output the following:

Your bill total is 256 dollars.

Instructions

1.
Following a recipe for vanilla cake, you are asked to add .75 ounces of vanilla extract; however,
you only have a teaspoon to measure the ingredients.

Create a function called ozToTsp() that takes a Double type argument named oz and returns a


Double type value.

Inside the function, create a variable tsp whose value is oz multiplied by 6. Use a return
statement to return the value of tsp.
Hint
To return a value from a function, add a return type to the function header.

If we had a function that took in an Int as an argument and a Boolean as a return value, our
header would look like this:

fun functionName(number: Int): Boolean {


  ...
}
To return the value, create a return statement with the return keyword:

return valueToReturn
2.
Inside main(), create a variable called tspNeeded and set its value to ozToTsp() with an argument
of .75.

Use println() and a String template to output the following statement:

You will need [tspNeeded] tsp of vanilla extract for this recipe.
Hint
To invoke the function, set it as the value of a variable:

var variable = functionName(.75)


// Write your code below

fun ozToTsp(oz: Double): Double {

var tsp = oz * 6

return tsp

fun main() {

// Write more code below

var tspNeeded = ozToTsp(.75)

println("You will need $tspNeeded tsp of vanilla extract for this recipe.")

}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Functions: Single Expression Functions

Narrative and Instructions

Learn
FUNCTIONS
Single Expression Functions
If one of our functions contains only a single expression, we can write the function out with
shorthand syntax. This syntax allows us to create a function using only a single line of code.

For example, assume we create a function that returns a given number (num) to the power of 2.
Using the normal function syntax, our code would look like this:

fun powerOf2(num: Int): Int {


  return num * num
}
Using the single expression function syntax, we can rewrite the above code by removing the
brackets ({ and }) as well as the return keyword:

fun powerOf2(num: Int): Int = num * num


Note how the return value (num * num) is prepended with an assignment operator (=).

We can shorten this code even more by removing the return type. Using type inference, the
compiler can deduce the type of the return value, making our function look like this:

fun powerOf2(num: Int) = num * num

Instructions

1.
Create a single expression function called pyramidVolume().

The function will accept three Int types arguments: l, w, and h and return the value of (l * w *
h) / 3.
Hint
If we needed a single expression function that returned the product of two numbers, our code
would look similar to the example below:

fun product(num1: Int, num2: Int) = num1 * num2


2.
Inside main(), create a variable called volume and set its value to pyramidVolume() with the
following arguments in their respective order: length, width, height.

Use println() and a String template to output the following:

The volume of this pyramid is [volume].


Hint
To invoke the function, set it as the value of a variable:

var variable = functionName(argumentValue)


When using a variable as an argument, add the variable name inside the parentheses of the
function.
// Write your code below

fun pyramidVolume(l: Int, w: Int, h: Int) = (l * w * h) / 3

fun main() {

var length = 5

var width = 8

var height = 14

// Write more code below

var volume = pyramidVolume(length, width, height)

println("The volume of this pyramid is $volume.")

My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Functions: Single Expression Functions

Narrative and Instructions

Learn
FUNCTIONS
Single Expression Functions
If one of our functions contains only a single expression, we can write the function out with
shorthand syntax. This syntax allows us to create a function using only a single line of code.

For example, assume we create a function that returns a given number (num) to the power of 2.
Using the normal function syntax, our code would look like this:

fun powerOf2(num: Int): Int {


  return num * num
}
Using the single expression function syntax, we can rewrite the above code by removing the
brackets ({ and }) as well as the return keyword:

fun powerOf2(num: Int): Int = num * num


Note how the return value (num * num) is prepended with an assignment operator (=).

We can shorten this code even more by removing the return type. Using type inference, the
compiler can deduce the type of the return value, making our function look like this:

fun powerOf2(num: Int) = num * num

Instructions

1.
Create a single expression function called pyramidVolume().

The function will accept three Int types arguments: l, w, and h and return the value of (l * w *
h) / 3.
Checkpoint 2 Passed

Hint
If we needed a single expression function that returned the product of two numbers, our code
would look similar to the example below:
fun product(num1: Int, num2: Int) = num1 * num2
2.
Inside main(), create a variable called volume and set its value to pyramidVolume() with the
following arguments in their respective order: length, width, height.

Use println() and a String template to output the following:

The volume of this pyramid is [volume].


Checkpoint 3 Passed

Hint
To invoke the function, set it as the value of a variable:

var variable = functionName(argumentValue)


When using a variable as an argument, add the variable name inside the parentheses of the
function.

// Write your code below

fun pyramidVolume(l: Int, w: Int, h: Int) = (l * w * h) / 3

fun main() {

var length = 5

var width = 8

var height = 14

// Write more code below

var volume = pyramidVolume(length, width, height)

println("The volume of this pyramid is $volume.")

}
FUNCTIONS
Function Literals
To simplify how we define functions, we can use function literals. A function
literal is an unnamed function that can be treated as a value: we can call them,
assign them as variables, pass them as arguments, and return them from a
function as we could with any other value.

We’ll be going over two types of function literals: anonymous functions and
lambda expressions. While anonymous functions and lambda expressions
serve the same purpose, they use a slightly different syntax.

To start, let’s create an anonymous function stored in a variable


called quotient that returns the quotient of two numbers:

val quotient = fun(num1: Int, num2: Int): Double { 


  return num1 / num2
}

 The anonymous function is contained in a variable called quotient.


 The fun keyword is placed after the assignment operator and is not
followed by a name (hence the anonymous).
 quotient has a function type of (Double, Double) -> Double.

The function type describes the argument type and return type of the
anonymous function. The arguments are contained within parentheses while
the return type is stated after ->. In this case, the anonymous function takes in
two Doubles and returns a single Double.

To call this anonymous function, we’ll simply call quotient like we would any


other variable:

println(quotient(10, 5)) // Prints: 2


A lambda expression is very similar to an anonymous function; however, its
concise syntax makes lambda expressions a more popular option amongst
programmers. It’s suggested to use a lambda expression over an anonymous
function when creating a function with only one expression.
If we were to recreate our quotient variable using a lambda expression, our
code would look like this:

val quotient = { num1: Int, num2: Int -> num1 / num2 }

println(quotient(10, 5)) // Prints: 2

 The lambda expression is contained within brackets: { and }


 We state the parameter names as well as their data types.
 The return value num1 / num2 is placed after the -> symbol.
 Including the return type is optional because the compiler can use type
inference to deduce the data type of the return value.

To learn more about anonymous functions and lambda expressions, check out
the Kotlin Language Guide.

Instructions

1.
Working at a landscape company, a customer asks for grass to cover the area
of their triangle-shaped yard.

Create a variable called area and sets its value to an anonymous function that


accepts two Int arguments: base and height and returns an Int value.

The return value should equal (base * height) / 2.

Use println() to output the value of area(15, 19).


Hint
The anonymous function should look similar to the example below:

var variableName = fun(arg1: Int, arg2: Int): Int { 


  // Add return statement here
}
2.
The customer comes back and asks for you to build a fence around their
garden.
Create a variable called perimeter and sets its value to a lambda expression
that accepts two Int values called side1 and side2 and returns an Int value.

The return value will equal the value of side1 + side2 times 2.

Use println() to output the value of perimeter(15, 24).


Hint
The lambda expression should look similar to the example below:

var variableName = { arg1: Int, arg2: Int, arg3: Int -> (arg1
+ arg2) * 2 }

landscape.kt

fun main() {

// Write your code below

// anonymous function

var area = fun(base: Int, height: Int): Int {

return (base * height) / 2

println(area(15, 19))

// lambda expression

var perimeter = {side1: Int, side2: Int -> (side1 + side2) * 2}

println(perimeter(15, 24))

}
FUNCTIONS
Review
Congratulations on completing this lesson. Let’s go over what we learned:

 A function is a reusable block of code that can be invoked throughout a program.


 In order to execute a function, it must be called somewhere in the program.
 An argument is a piece of data fed to the function.
 Arguments have the option to be named and/or given default values.
 A return statement returns a piece of data from the function to where the
function was called.
 Functions with only a single expression can be written with a single line of code
using shorthand syntax.
 A function literal is an unnamed function that can be passed as an expression.
https://www.codecademy.com/courses/learn-kotlin/projects/kotlin-functions-project

https://www.codecademy.com/courses/learn-kotlin/lessons/kotlin-using-text-variables/exercises/user-
input

https://www.codecademy.com/courses/learn-kotlin/articles/kotlin-recursion

https://en.wikipedia.org/wiki/Stack_overflow
https://www.codecademy.com/courses/learn-kotlin/lessons/kotlin-classes/exercises/introduction-to-
classes

claas of kotlin

My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Classes: Creating a Class

Narrative and Instructions

Learn
CLASSES
Creating a Class
Now let’s practice writing our own classes. A Kotlin class is declared at the top of a Kotlin file,
outside the main() function, with the class keyword followed by its name:

class Name {
// class body
}
The name of a class should always start with an upper case letter and use the camel case form.
The class body is contained within curly braces and will hold all of the properties and functions
related to that class. We will take a closer look at class functions in a later exercise.

Note: It is optional for a Kotlin class to contain a body, thus if the class has no body, we can
omit its curly braces, resulting in the following declaration:

class Name
Let’s revisit our real-world, Car example. Suppose we create the following class:

class Car  
Our blueprint is complete! But it’s not of much use to us empty. Any car possesses several
properties including the year it was made, its model name, and color. Let’s add these:
class Car {
val year = 2011
val model = "Jeep"
val color = "Blue"
}
We’ve created the properties, year, model, and color and initialized them with values. Now any
time we create a car object from this class, it will possess the
properties, year, model and color and hold their respective values. In the next exercise, we’ll
learn how to create objects from a class. For now, let’s practice with the Kotlin class syntax. 🚗

Instructions

1.
In Book.kt, declare an empty class called Book.
Checkpoint 2 Passed

Hint
An empty class can be created with the following syntax:

class Name {

}
2.
Add the following properties and the values they hold:

 pages with the value, 320


 title with the value, "Harry Potter and the Sorcerer's Stone"
 author with the value, "J.K. Rowling"
Checkpoint 3 Passed

Hint
A book has a total number of pages, possesses an author and a title. We can use these properties
within our class as so:

class Name {
var property1 = 320
var property2 = "Harry Potter and the Sorcerer's Stone"
var property3 = "J.K. Rowling"
}

class Book {

var pages = 320


var title = "Harry Potter and the Sorcerer's Stone"

var author = "J.K. Rowling"

// Write your code above 📕

fun main() {

}
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Classes: Creating an Instance

Narrative and Instructions

Learn
CLASSES
Creating an Instance
Now that we’ve created our first class, let’s create an instance of it. An instance of a class
resembles an object that is a member of that given class.

Recall the Car class from the previous exercise:

class Car {
val year = 2011
val model = "Jeep"
val color = "Blue"
}
To make an instance of this class, we’d utilize the following syntax:

val myCar = Car()

 We’ve declared the name of our instance/object to be myCar. This name is arbitrary and is
up to the developer’s choosing.
 Following the assignment operator, we’ve invoked the Car class with the name of the
class followed by parentheses - the same syntax we use when invoking a function.
 With this line of code, the myCar instance now possesses all the properties and their
respective values that were specified within the class body.

Just like we’ve done with Kotlin’s built-in properties such as .length and .size, we can utilize
the dot notation and append our class property names on our instance/object and retrieve their
values.

println(myCar.year)  // Prints: 2011


println(myCar.model) // Prints: Jeep
println(myCar.color) // Prints: Blue
Voila! You’ve created your first object. Think about what you’ve learned about classes and their
properties. What is one way that we might need to improve upon with this code? Follow the
checkpoints below to find out.

Instructions

1.
Within the main() function of Building.kt, create an instance of the Building class and assign it
to the variable, residentialBuilding.
Checkpoint 2 Passed

Hint
Implement the following syntax in your code:

var instanceName = className()


2.
Create three print statements that use dot notation to output each value of the
instance, residentialBuilding.
Checkpoint 3 Passed

Hint
Use the following syntax for each property call:

println(instanceName.yearBuilt) // Prints: 2016


3.
Optional:

If you create another instance of the Building class, say commercialBuilding, and output its


property values, what do you expect to see?

Check the Hint for a clue.


Checkpoint 4 Passed

Hint
With each and every instance created for the Building class, the values will always be 2016, 400,
and "Limestone". This may work for some programs but not for most where we’d most likely
need to have custom values set for each instance. There’s a very small chance that one residential
building has the same exact characteristics as another commercial building!

In the next exercise, we’ll explore how to customize these values.

class Building {

val yearBuilt = 2016

val height = 400 // Feet

val type = "Limestone"

}
fun main() {

// Write your code below 🏙

var residentialBuilding = Building()

println(residentialBuilding.yearBuilt)

println(residentialBuilding.height)

println(residentialBuilding.type)

}
class Building {

val yearBuilt = 2016

val height = 400 // Feet

val type = "Limestone"

fun main() {

// Write your code below 🏙

var residentialBuilding = Building()

println(residentialBuilding.yearBuilt)

println(residentialBuilding.height)

println(residentialBuilding.type)

}
CLASSES
Primary Constructor
Looking to customize your instances? You’ve come to the right place! Kotlin
classes provide us with something called a primary constructor that allows us
to declare properties and initialize them when we instantiate an object.

Let’s see the shorthand syntax:

class Name(val x: String, val y: String)


We’ve now introduced a pair of parentheses in the class header that define
properties, x and y. Previously, we would’ve had something like this:

class Name {
  val x = "some value"
  val y = "another value"
}
Each property would already have its default value set, but with primary
constructors, we give our program the ability to set the values when an
instance is created.

Refactoring our Car example from the previous exercise to utilize a primary


constructor in the header, we get the following line of code:

class Car(val year: Int, val model: String, val color: String)
Neat, right? Let’s see it in action.

val myCar = Car(2011, "Jeep", "Blue")


val friendsCar = Car(2015, "Mazda", "Red")
Now we’ve successfully created unique instances of our Car class and
customized their values:

println(myCar.year)      // Prints: 2011


println(friendsCar.year) // Prints: 2015

Instructions

1.
In Person.kt, add a class, Person that contains a primary constructor with the
following properties:
 name with the type, String
 age with the type, Int
 favoriteColor with the type, String

Hint
Keep the following syntax in mind when creating your class:

class Name(val property1: String, val property2: Int, val


property3: String)
2.
Within the main() function, create an instance of the Person class called me and
set the values for each property that resemble your characteristics.

On the following line, create another instance of the Person class


called myFriend and set the values for each property that resemble their
characteristics.
Hint
Make sure to create two separate instances with custom values:

val instance1 = Person("Maggie", 26, "Green")


val instance2 = Person("Jose", 25, "Red")
3.
Use a String template along with a println() statement for each object and
output the following text:

[name] is [age] years old and ___ favorite color is


[favoriteColor].
Make sure to replace the ___ with the appropriate pronoun (my, her, his,
or their) to match the instance. Check the hint for guidance.
Hint
Implement the following syntax in your code:

println("${instance1.name} is ${instance1.age} years old and my


favorite color is ${instance1.favoriteColor}.")

println("${instance2.name} is ${instance2.age} years old and


their favorite color is ${instance2.favoriteColor}.
// Write your class below

class Person(val name: String, val age: Int, val favoriteColor: String)

fun main() {

// Create your instances below

val me = Person("Maggie", 26, "Green")

val myFriend = Person("Jose", 25, "Red")

println("${me.name} is ${me.age} years old and my favorite color is ${me.favoriteColor}.")

println("${myFriend.name} is ${myFriend.age} years old and their favorite color is $


{myFriend.favoriteColor}.")

}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Classes: Member Functions

Narrative and Instructions

Learn
CLASSES
Member Functions
Now let’s explore how to add even more functionality to our classes with functions. A function
declared within a Kotlin class is known as a member function.

Member functions possess the same qualities and abilities as the user-designed functions you’ve
learned about in the previous lesson. The syntax is the same as well. Some things to keep in
mind:

 When an instance of a class is created, the object has access to any and all functions that
exist within the class body.
 Unlike the code within the init block which executes automatically, the code within the
functions will only execute when the function is called.

For example,

class Cat(val name: String, val breed: String) {

  fun speak() {
    println("Meow!")
  }
}
We’ve created a simple class, Cat, with a primary constructor and a single member function. We
can now create an instance of the class as so and call the speak() function:

var myCat = Cat("Garfield", "Persian")


myCat.speak() // Prints: Meow!
🐈

Instructions
1.
Inspect the class, Dog, on the right. Inside the init block, we looped through the list
property, competitionsParticipated. Now, let’s add a member function below the init block that
shows off one of the dog tricks done in the competition.

Add a member function called, speak(), that outputs the following text:

[name] says: Woof!


Hint
Make sure to use the following syntax in your function code:

fun speak() {
  println("$dog says: Woof!")
}
2.
Create an instance of the Dog class within the main() function. Call the instance, maxie. Pass in the
following custom values for the properties:

 name: "Maxie"
 breed: "Poodle"
 list of competitions should include "Westminster Kennel Club Dog
Show" and "AKC National Championship"

Run your code. Then, call the speak() function on maxie on the following line.
Hint
Within the main() function, add the following instance:

var dogName = Dog("Maxie", "Poodle", listOf("Westminster Kennel Club


Dog Show", "AKC National Championship"))
Next, call the function:

dogName.speak()
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools

Classes: Member Functions

Narrative and Instructions

Learn
CLASSES
Member Functions
Now let’s explore how to add even more functionality to our classes with functions. A function
declared within a Kotlin class is known as a member function.

Member functions possess the same qualities and abilities as the user-designed functions you’ve
learned about in the previous lesson. The syntax is the same as well. Some things to keep in
mind:

 When an instance of a class is created, the object has access to any and all functions that
exist within the class body.
 Unlike the code within the init block which executes automatically, the code within the
functions will only execute when the function is called.

For example,

class Cat(val name: String, val breed: String) {

  fun speak() {
    println("Meow!")
  }
}
We’ve created a simple class, Cat, with a primary constructor and a single member function. We
can now create an instance of the class as so and call the speak() function:

var myCat = Cat("Garfield", "Persian")


myCat.speak() // Prints: Meow!
🐈

Instructions
1.
Inspect the class, Dog, on the right. Inside the init block, we looped through the list
property, competitionsParticipated. Now, let’s add a member function below the init block that
shows off one of the dog tricks done in the competition.

Add a member function called, speak(), that outputs the following text:

[name] says: Woof!


Checkpoint 2 Passed

Hint
Make sure to use the following syntax in your function code:

fun speak() {
  println("$dog says: Woof!")
}
2.
Create an instance of the Dog class within the main() function. Call the instance, maxie. Pass in the
following custom values for the properties:

 name: "Maxie"
 breed: "Poodle"
 list of competitions should include "Westminster Kennel Club Dog
Show" and "AKC National Championship"

Run your code. Then, call the speak() function on maxie on the following line.
Checkpoint 3 Passed

Hint
Within the main() function, add the following instance:

var dogName = Dog("Maxie", "Poodle", listOf("Westminster Kennel Club


Dog Show", "AKC National Championship"))
Next, call the function:

dogName.speak()

dog.kt

class Dog(val name: String, val breed: String, val competitionsParticipated: List<String>) {

init {

for (comp in competitionsParticipated) {

println("$name participated in $comp.")

}
}

// Write your function below

fun speak() {

println("$name says: Woof!")

fun main() {

// Write your instance below 🐩

var maxie = Dog("Maxie", "Poodle", listOf("Westminster Kennel Club Dog Show", "AKC National
Championship"))

maxie.speak()

}
CLASSES
Review
Excellent work! In this lesson, we’ve learned the following concepts:

 A class is an object-oriented concept which resembles a blueprint for individual objects.


A class can contain properties and functions and is defined using the class keyword
followed by a name and optional body.
 An instance is a member of a class created by calling the class name followed by a pair of
parentheses, (), and any necessary arguments.
 We can use dot syntax to access the value of each class property.
 A class can have properties with default values or ones that are customizable with the
help of primary constructors.
 A primary constructor allows us to set each property value when we instantiate an object.
 The init block gets invoked with every instance creation and is used to add logic to the
class.
 A function declared within a Kotlin class is known as a member function of that class. In
order to invoke a member function, we must call the function on an instance of the class.

Instructions

You did it! 🎉 You’ve completed the last lesson in the Learn Kotlin course. You should be
immensely proud of yourself and your accomplishments. This was no easy feat, but you’ve made
it to DevCity and can proudly say you’re on track to becoming a master of the Kotlin language.

Run the code on the right and enter the following two commands for a special message from
Codey:

kotlinc Congratulations.kt -include-runtime -d Congratulations.jar


java -jar Congratulations.jar

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


Code Editor

Run
Terminal

7/7
Back
class Congratulations(val name: String) {
init {

println("Dear $name,")

fun message() {

println("Thank you for embarking on this journey with me. I couldn't have gotten through the
treacherous waters of Conditional Creek or hiked up the Looping mountains without your help. You now
have the fundamental knowledge to go on and continue your Kotlin journey in the world of android
application, web development or more. The world is yours. Good luck! ")

fun signOut() {

println("With ♥️, Codey and the Codecademy Team.")

fun main() {

println("Please enter your name...")

var learnerName = readLine()

var toLearner = Congratulations(learnerName.toString())

toLearner.message()

toLearner.signOut()

}
class
Calculator(va
l name:
String) {
init {
println("$name's Calculator 🧮")
}

fun add(a: Int, b: Int): Int {


return a + b
}

fun subtract(a: Int, b: Int): Int {


return a - b
}

fun multiply(a: Int, b: Int): Int {


return a * b
}

fun divide(a: Int, b: Int): Any {


if (b == 0) {
return "Error! Dividing by zero is not allowed."
} else {
return a / b
}
}

fun power(a: Int, b: Int): Int {


var result = 1
for (i in 1..b) {
result *= a
}
return result
}
}

fun main() {
var myCalculator = Calculator("Codey")
println(myCalculator.add(5, 7))
println(myCalculator.subtract(45, 11))
println(myCalculator.divide(8, 0))
println(myCalculator.power(2, 1))
}

 © 2021 GitHub, Inc.


 Terms
 Privacy
 Security
 Status
 Docs

 Contact GitHub
 Pricing
 API
 Training
 Blog
 About
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools

Learn Kotlin: Codey's Calculator

Brief

Objective
LEARN KOTLIN
Codey's Calculator
Codey’s made it to DevCity: a place full of Android applications, web development, and other
endless implementations of the Kotlin language!

In this project, we’ll utilize our knowledge of Kotlin classes to help Codey build a basic
calculator application that many of us have built-into our smartphones.

Our calculator will be able to:

 Find the sum +


 Find the difference -
 Find the product ✕
 Find the quotient ÷
 Find the power ^

A variation of this project exists in our Learn Java course so if you’re learning Kotlin with a Java
background, we highly recommend comparing the syntaxes and code implementations once
you’ve completed this project to better understand the similarities and differences between the
two languages.

Let’s get to calculating! 🧮

Tasks

12/13 Complete
Mark the tasks as complete by checking them off
Create a Class
1.
The first step in creating Codey’s individual calculator is to generate a blueprint.

In Calculator.kt, declare the class, Calculator, that accepts a name property within its primary
constructor.

Note: Running your code will result in the following error:

could not find or load main class CalculatorKt


This error exists due to the absence of a main() function. If you’d like to get rid of this error now,
go ahead and also create an empty main() function below the class. Otherwise, move on to the
next step.
Hint
At the top of the Calculator.kt file, declare a class using the following syntax:

class Name
To add a primary constructor with a single property, make sure to implement the following code
and specify the property type:

class Name(val propertyName: String)


2.
Within the class body, add an init block that will output the owner of the calculator using
the name property.
Hint
Here’s one example of how you can construct your init block:

init {
  println("$name's Calculator 🧮")
}
String concatenation can also be used in your statement instead.
Add the Calculator's Functions
3.
Now, let’s give our calculator the ability to make calculations.

First, declare a member function called, add(), which should calculate and return the sum of two
Integer values.
Hint
Mimic the following function header in your code:

fun add(param1: Int, param2: Int): Int {


Within the function, add a return keyword followed by a sum calculation:

return param1 + param2


4.
Next, implement the subtract() function which should calculate and return the difference
between two Integer values.
Hint
Mimic the following function header in your code:

fun subtract(param1: Int, param2: Int): Int {


Within the function, add a return keyword followed by a difference calculation:

return param1 - param2


5.
Another arithmetic function most commonly used on a calculator is multiplication.

Implement the multiply() function which will calculate and return the product between two
Integer values.
Hint
Mimic the following function header in your code:

fun multiply(param1: Int, param2: Int): Int {


Within the function, add a return keyword followed by a multiplication calculation:

return param1 * param2


6.
The opposite calculation of multiplication is division. Add a member function, divide(), which
should calculate and return the quotient between two Integer values.

The member function should return an error message if the user tries to divide by 0.
Hint
Mimic the following function header in your code:

fun divide(param1: Int, param2: Int): Any {


Within the function, add an if-else expression in the following form that checks if the second
parameter is 0:

if (param2 == 0) {
  return "Error! Dividing by zero is not allowed."
} else {
  return param1 / param2
}
Notice how because the conditional can return either a String or Int type, it was important for us
to specify Any in the function header.
7.
Lastly, create the power() function which should calculate and return the first parameter raised to
the power of the second.

Think of how you can implement this within the function body. Give it a shot in the code editor.
Move on to the next step for guided instruction.
Hint
Use the following syntax to create the power() function:

fun power(param1: Int, param2: Int): Int {


// Code will go here
}
8.
Within the body of the power() function, declare a new variable, result, and assign it the value
of 1.

To achieve the power calculation, use a looping technique to iterate over each value, from 1 to
param1. Within the body of the loop, reassign the value of result to be result times param2.

Return result from the function.


Hint
Use a for loop along with a range, 1..param2, to perform the calculation. Within the loop, an
augmented assignment operator can be used to multiply and reassign the new value to result.

If your first parameter is x and your second parameter is y, we can set up the following code:

var resultVar = 1

for (i in 1..y) {
  resultVar *= x
}

return resultVar
Get to Calculating
9.
Now that we’ve implemented several arithmetic functionalities, let’s spring our calculator to
action. If you haven’t already done so, below the class, declare a main() function.

In it, create a variable name of your choosing that will store an instance of the Calculator class.
Pass in the name, "Codey" in the class call, and run your code. You should see the output
statement from the init block.
Hint
Utilize the following syntax in your object creation:

var myCalculator = Calculator("Name here")


10.
On the following line, call the add() function on your instance and pass in two Integer values
consecutively. Wrap your code in a println() statement to see the output.
Stuck? Get a hint
11.
Use the same syntax to call each member function on your instance on a separate line and test
their calculations. Make sure to wrap each line of code in a println() statement to see the output.
Hint
Each member function can be called on the instance as so:

println(myCalculator.subtract(45, 11))
// Prints: 34

println(myCalculator.divide(8, 0))
// Prints: Error! ...

println(myCalculator.power(2, 1))
// Prints: 2 
Optional Challenges
12.
Excellent work! If you’re up for a challenge, check out these additional tasks:

 To mimic a real-world calculator, we can format our output to also include the original
calculation. 12 -> 5 + 7 = 12.
 Having the code as is without any additional output, we can refactor some of the member
functions to utilize a single expression syntax and shorten the lines of code that they span.
 We can add another member function to the class that you’d like your calculator to
perform.

Hint
For the first task, we can utilize print() statements and String templates to add a line of code
similar to this one to the top of each function:

print("$param1 + $param2 = ")


For the second task, if we choose to not add any print statements and instead keep the body of
the first few member functions containing just a return, we can implement this shorter, more
concise syntax:

fun add(a: Int, b: Int): Int = a + b


For the third task, we can add a member function that calculates the percent of an Integer, such
as 50% of 20 which would return 10.

To do so, we’d need to accept the percent number in Int form and then convert it to decimal
within the function:

var decimalForm = num * 0.01


Then, we’d multiply this result by the second parameter and return the answer.
Solution
13.
Sample solution:

 Calculator.kt

If you make something cool, share it with us!


Hint
Tag @Codecademy on Twitter or make a Pull Request to the Learn Kotlin GitHub repo for a
chance be featured in the course.

class Calculator(val name: String) {

init {

println("$name's Calculator 🧮")

fun add(a: Int, b: Int): Int {

return a + b

fun subtract(a: Int, b: Int): Int {

return a - b

fun multiply(a: Int, b: Int): Int {

return a * b

fun divide(a: Int, b: Int): Any {

if (b == 0) {
return "Error! Dividing by zero is not allowed."

} else {

return a / b

fun power(a: Int, b: Int): Int {

var result = 1

for (i in 1..b) {

result *= a

return result

fun main() {

var myCalculator = Calculator("Codey")

println(myCalculator.add(5, 7))

println(myCalculator.subtract(45, 11))

println(myCalculator.divide(8, 0))

println(myCalculator.power(2, 1))

}
Sample

https://github.com/Codecademy/learn-kotlin/blob/main/7-classes/Calculator.kt

You might also like