Kotlin. Loop for. Implementation methods

Loop for. Ways of implementation. Applying a for loop to ranges, arrays, lists, dictionaries, sets


Contents


Search other resources:

1. Loop for. Ways for implementation. General form

In Kotlin, the for loop is similar to the foreach loop in the Java, C# programming languages. It allows you to traverse the values of the elements of a collection, array, range, or other set of values. The values of an object that contains a set of elements can be traversed in forward and backward directions. You can also specify a step when traversing values.

If the elements of a set are traversed in the forward direction, then the general form of the cycle is as follows

for (varIter in IterObj step stepValue) {
  // Statements
  // ...
}

here

  • IterObj is an object containing or defining a set of values to be traversed sequentially from first to last. Such an object can be a list, an array, a range, etc.;
  • varIter is an iterator variable that takes values from the IterObj set one by one. Within the body of the for loop, Statements are executed for each new varIter value;
  • Statements – one or more instructions executed at each iteration;
  • stepValue – step for traversing the range values. stepValue must be a positive integer.

If the traversal step is 1, the fragment step = stepValue can be omitted

for (varIter in IterObj) {
  // Statements
  // ...
}

If it is necessary to get an enumeration of values within the specified limits in the reverse order, then the form of the for statement with the downTo keyword is used for this.

for (varIter in BeginValue downTo EndValue step stepValue) {
  // Statements
  // ...
}

here

  • varIter – iteration counter variable;
  • BeginValue, EndValue – the first and last values, considered in reverse order;
  • stepValue – step for changing the varIter counter. stepValue must be a positive integer.

If stepValue is 1, then this fragment can be omitted. In this case, the for loop will look like this

for (varIter in BeginValue downTo EndValue) {
  // Statements
  // ...
}

 

2. Examples of solving tasks using the for loop
2.1. Range traversal

The simplest task is to traverse a range of numbers in forward and backward order.

fun main(args:Array<String>)
{
  // Range traversal
  // 1. Specified range of integers
  val ir : IntRange = 0..10

  // 2. Get squares of numbers out of range
  for (t in ir)
    print((t*t).toString()+" ")

  // 3. Display the squares of paired numbers in a range
println()
  for (t in ir step 2)
    print((t*t).toString()+" ")

  // 4. Print the squares of paired numbers in a range in reverse order
  println()
  for (t in ir.last downTo ir.first step 2)
    print((t*t).toString()+" ")
}

The result of the program

0 1 4 9 16 25 36 49 64 81 100
0 4 16 36 64 100
100 64 36 16 4 0

 

2.2. List traversal

The following example shows the processing of a list of strings and a list of numbers.

fun main(args:Array<String>)
{
  // List traversal
  // 1. Specified list of strings
  val ls : List<String> = listOf("abc", "abcd", "jklmn", "joprst", "pupkin", "ddeee")

  // 2. Display the list
  for (s in ls)
    print(s + " ")

  // 3. In the given list, calculate the position of the first line with the longest length.
  var maxLen : Int
  var posMaxLen : Int
  var i : Int

  i = 0
  posMaxLen = 0
  maxLen = ls[posMaxLen].length

  for (s in ls) {
    if (maxLen < s.length) {
      posMaxLen = i
      maxLen = s.length
    }
    i++
  }
  println()
  print("posMaxLen = " + posMaxLen + ", " + "maxLen = " + maxLen)

  // 4. Display the list of strings in reverse order
  println()
  for (s in ls.reversed())
    print(s + " ")

  // 5. In the given list of integers, calculate the sum of the elements
  //   that are located at odd positions 1, 3, 5,….   
  // Consider that the numbering of positions starts from 0.   
  // 5.1. Specified list   
  val lstInt : List<Int> = listOf(2, 4, 3, 8, 2, 1, 5, 7, 9, 3)
  var pos : Int
  var summ : Int

  // 5.2. Loop through the list.
  pos = 0
  summ = 0
  for (i in lstInt) {
    if (pos % 2 == 1)
      summ += i
    pos++
  }

  // 5.3. Display the result
  println()
  println("lstInt = " + lstInt)
  println("summ = " + summ)
}

The result of the program

abc abcd jklmn joprst pupkin ddeee
posMaxLen = 3, maxLen = 6
ddeee pupkin joprst jklmn abcd abc
lstInt = [2, 4, 3, 8, 2, 1, 5, 7, 9, 3]
summ = 23

 

2.3. Traversing the elements of the Map dictionary

Demonstrates traversing parts of the dictionary in forward and backward order. The example demonstrates the capabilities of the for loop, not the capabilities of working with dictionaries.

fun main(args:Array<String>)
{
  // Traversing dictionary elements
  // 1. A dictionary is specified in which pairs are defined: number of the day of the week -> name of the day of the week   
  // 1.1. Declare a variable of type dictionary <Int, String>
  var days : Map<Int, String> = mapOf()

  // 1.2. Add value to dictionary
  days = days + mapOf(Pair(1, "Monday"))
  days = days + mapOf(Pair(2, "Tuesday"))
  days += mapOf(Pair(3, "Wednesday"))
  days += mapOf(Pair(4, "Thursday"))
  days += mapOf(Pair(5, "Friday"))
  days += mapOf(Pair(6, "Saturday"))
  days += mapOf(Pair(7, "Sunday"))

  // 2. Dictionary traversal and outputting values
  for (d in days)
    print(d.toString() + " ")
  println()

  // 3. Displaying dictionary values in reverse order
  for (d in days.keys.reversed())
    print(d.toString() + "=" + days[d] + " ")
  println()
}

Program result

1=Monday 2=Tuesday 3=Wednesday 4=Thursday 5=Friday 6=Saturday 7=Sunday
7=Sunday 6=Saturday 5=Friday 4=Thursday 3=Wednesday 2=Tuesday 1=Monday

 

2.4. Set traversal

This example demonstrates the use of a for loop to traverse a set. All the possibilities of sets are not disclosed here.

fun main(args:Array<String>)
{
  // Traversing the elements of a set
  // 1. The specified set
  val Colors = setOf("Red", "Blue", "Green", "Yellow")

  // 2. Display the elements of the set
  for (c in Colors)
    print(c + " ")
  println()

  // 3. Display elements of a set in reverse order
  for (c in Colors.reversed())
    print(c + " ")
  println()
}

Program result

Red Blue Green Yellow
Yellow Green Blue Red

 

2.5. Traversing the Array. Calculating the sum of elements in an array according to a condition

The example demonstrates the use of a for loop for the following tasks:

  • traversal of array elements and their output in direct order;
  • traversal of array elements and their output in reverse order;
  • calculating the sum of array elements;
  • calculating the sum of paired elements of an integer array;
  • calculating the sum of array elements lying in even positions.

 

fun main(args:Array<String>)
{
  // Traversing the array of numbers.
  // 1. A specified array of numbers
  var A : Array<Int> = arrayOf(10, 20, 33, 17, 35, 11, 22)
  var i:Int
  var n:Int

  // 2. Traversing the array in direct order
  for (i in A) {
    print(i.toString() + " ")
  }
  println()

  // 3. Traversing the array in reverse order
  for (i in A.reversedArray()) {
    print(i.toString() + " ")
  }
  println()

  // 4. Calculate the sum of the elements of the array.
  var summ = 0
  for (i in A) {
    summ += i
  }
  println("summ = " + summ)

  // 5. Calculate the sum of the paired elements of an array.
  summ = 0
  for (i in A)
    if (i%2 == 0)
      summ += i
  println("summPair = " + summ)

  // 6. Calculate the sum of elements that are placed in paired positions (0, 2, 4, ...)
  var pos = 0
  summ = 0
  for (i in A) {
    if (pos%2==0)
    summ += i
    pos++
  }
  println("summPairPos = " + summ)
}

The result of the program

10 20 33 17 35 11 22
22 11 35 17 33 20 10
summ = 148
summPair = 52
summPairPos = 100

 


Related topics