Kotlin. Loops. Basic concepts. The while, do-while loops

Loops. Basic concepts. The while, do-while loops. Examples of tasks solving


Contents


Search other resources:

1. The concept of loop

Very often, Kotlin programs require multiple repetitions of one or more statements. This repetition process is called a cyclical process or cycle. During the execution of the loop, the piece of code that defines the iteration of the loop is executed many times. The number of iterations performed in a loop depends on the fulfillment (not fulfillment) of a certain condition.

Like any other language, Kotlin has convenient tools for organizing a looping process. These facilities include three types of loop statements:

  • loop operator while. This operator is used when you want the loop execution condition to follow before the iteration;
  • loop operator do-while. It provides the implementation of a cyclic process, in which the loop iteration is performed first, and only then the condition is checked for the possibility of performing the next iteration;
  • the for statement. This statement is analogous to the for-each loop in the Java, C# languages. It traverses the elements of the collection.

 

2. Loop while. The general concepts

The while loop operator is also called the precondition loop operator. The general form of the while loop statement is as follows:

while (condition)
{
  // Statements
  // ...
}

here

  • condition – a conditional expression that determines the need to execute the loop body;
  • Statements – one or more instructions (operators) executed in a block of curly braces { }. If you need to execute one statement, then the curly braces can be omitted.

In the while statement, the conditional expression condition is first checked. If condition is true, then statements in curly braces are executed. Otherwise, the execution of the while loop operator is terminated and control is transferred to the next operator.

 

3. Examples of solving tasks using the while loop
3.1. Forming a number of numbers according to a given condition

Task. Print those natural numbers, the square of which does not exceed the value n.

Solution.

fun main(args:Array<String>)
{
  // 1. Declaring variables
  var i:Int = 1
  var n:Int

  // 2. Input n
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Loop for calculating the values of numbers
  while (i*i < n)
  {
    print(i.toString()+" ")
    i = i+1
  }
}

Test example

n = 150
1 2 3 4 5 6 7 8 9 10 11 12

 

3.2. Calculating the sum of a series of numbers

Task. Using a while loop, calculate the sum of the numbers in the sequence given by the formula

2 + 5 + ... + 3*n-1

where the value of n is specified from the keyboard.

For example, for n = 5, you need to calculate the sum

s = 2 + 5 + 8 + 11 + 14

Solution.

fun main(args:Array<String>)
{
  // Calculation of the summ. The while loop
  // 1. Declare the variables
  var i:Int
  var n:Int
  var s:Int

  // 2. Entering the n value
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Sum calculation loop
  s = 0
  i = 1
  while (i <= n)
  {
    s += 3*i-1
    i = i+1
  }

  // 4. Print the result
  println("s = " + s)
}

Test example

n = 8
s = 100

 

3.3. Determination of the maximum digit in the integer number

Task.

A natural number n is given. Determine the maximum digit in this number.

Solution.

fun main(args:Array<String>)
{
  // Calculating the maximum digit of a number
  // 1. Declare the variables
  var i:Int
  var n:Int
  var maxNumber:Int

  // 2. Input number
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Digit determination loop
  maxNumber = 0
  i = n
  while (i>0)
  {
    if (maxNumber<i%10)
      maxNumber = i%10
    i = i / 10
  }

  // 4. Input the result
  println("maxNumber = " + maxNumber)
}

Test example

n = 452723
maxNumber = 7

 

4. The loop do-while. General form

The do-while loop is also called a postcondition loop. The general form of the do-while loop operator looks like this:

do
{
  // Statements
  // ...
} while (condition)

here

  • Statements – one or more statements executed in the loop;
  • condition is a conditional expression that determines the need to execute the next iteration of the loop.

The do-while loop works as follows. First, the body of the loop is executed, enclosed in curly braces { }. The body of the loop can contain one or more statements. Then the value of the conditional expression condition is checked. If the value of the conditional expression is true, the transition to the next iteration of the loop occurs. Otherwise, the execution of the do-while statement ends.

 

5. Examples of solving tasks using the do-while loop
5.1. Calculating the sum of a sequence of numbers

Task. You are given a non-empty sequence of numbers terminated by zero. You need to calculate the sum of all the numbers in the sequence.

Solution. For tasks like this, where you first need to get a value to test, a do-while loop is best suited.

fun main(args:Array<String>)
{
  // Calculate the sum of the numbers in a sequence

  // 1. Declare variables
  var number = 0
  var summ = 0

  // 2. Loop for entering numbers and calculating the sum
  do
  {
    // Add a number to the sum
    summ += number

    // Get a number
    print("number = ")
    number = readLine().toString().toInt()
  } while (number!=0)

  // 3. Print the result
  println("summ = " + summ)
}

Test example

number = 8
number = 4
number = 5
number = 6
number = 0
summ = 23

 

5.2. A combination of a do-while loop and an if-else-if statement. Calculating the maximum values in a sequence of numbers

Task.

An integer n (n≥3) and a sequence of real numbers a1, a2, …, an are given, which are entered from the keyboard. Calculate the two maximum numbers in a sequence.

Solution.

fun main(args:Array<String>)
{
  // Calculation of two maximum numbers of a sequence a1, a2, ..., an   
  // 1. Declare variables
  var max1:Double = 0.0
  var max2:Double = 0.0
  var n:Int
  var number:Double
  var i:Int
  var fFirst:Boolean

  // 2. Input number n
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Loop for inputting numbers and calculating maximum values
  i = 0
  do {
    print("number = ")
    number = readLine().toString().toDouble()

    if (i==0) {
      max1 = number
      max2 = number
    }
    else
    if (i==1)
    {
      if (max1<number)
        max1=number
      else
        max2=number
    }
    else
    {
      if (max1<number) {
        max2 = max1
        max1 = number
      }
      else
        if (max2<number)
          max2 = number
    }
    i++
  } while (i<n)

  // 4. Print the result
  println("max1 = " + max1)
  println("max2 = " + max2)
}

Test example

n = 6
number = 2
number = 4
number = 2
number = 3
number = 5
number = 2
max1 = 5.0
max2 = 4.0

 

5.3. Fibonacci series

Task. Form a Fibonacci series containing n numbers (n≥3). The number of numbers in the series is set from the keyboard. For example, for n = 7 the series will look like this:

0, 1, 1, 2, 3, 5, 8

Solution.

fun main(args:Array<String>)
{
  // Formation of the Fibonacci series
  // 1. Declare variables
  var x1:Int
  var x2:Int
  var x3:Int
  val n:Int
  var i:Int

  // 2. Input number n
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Checking n for correctness
  if (n<3) {
    println("Incorrect input.")
    return
  }

  // 3. Setting initial values 0, 1 and outputting them
  x1=0
  x2=1
  print(x1.toString()+" ")
  print(x2.toString()+" ")

  // 4. The cycle of the formation of a series and its output
  i=2
  do {
    x3=x1+x2
    print(x3.toString() + " ")
    x1=x2
    x2=x3
    i++
  } while (i<n)
}

Test example

n = 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

 


Related topics