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 is a 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 as the loop variable.
  • The range 1 through 5 as the iterator.
  • a println() in the loop body.
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, Codey! i = 1 Hello, Codey! i = 2 Hello, Codey! i = 3 Hello, Codey! i = 4 Hello, Codey! i = 5
Folder Icon

Take this course for free

Already have an account?