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

### Contents

- 1. The concept of loop
- 2. Loop while. The general concepts
- 3. Examples of solving tasks using the while loop
- 4. The loop do-while. General form
- 5. Examples of solving tasks using the do-while loop
**Related topics**

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

funmain(args:Array<String>) {// 1. Declaring variablesvari:Int = 1varn:Int// 2. Input n"n = ") n =readLine().toString().toInt()// 3. Loop for calculating the values of numberswhile(i*i < n) {" ") 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****.**

funmain(args:Array<String>) {// Calculation of the summ. The while loop // 1. Declare the variablesvari:Intvarn:Intvars:Int// 2. Entering the n value"n = ") n =readLine().toString().toInt()// 3. Sum calculation loops = 0 i = 1while(i <= n) { s += 3*i-1 i = i+1 }// 4. Print the resultprintln("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****.**

funmain(args:Array<String>) {// Calculating the maximum digit of a number // 1. Declare the variablesvari:Intvarn:IntvarmaxNumber:Int// 2.Input number"n = ") n =readLine().toString().toInt()// 3. Digit determination loopmaxNumber = 0 i = nwhile(i>0) {if(maxNumber<i%10) maxNumber = i%10 i = i / 10 }// 4. Input the resultprintln("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.

funmain(args:Array<String>) {// Calculate the sum of the numbers in a sequence// 1. Declare variablesvarnumber = 0varsumm = 0// 2. Loop for entering numbers and calculating the sumdo{// Add a number to the sumsumm += number// Get a number"number = ") number =readLine().toString().toInt() }while(number!=0)// 3. Print the resultprintln("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 *a*_{1}, *a*_{2}, …, *a*_{n} are given, which are entered from the keyboard. Calculate the two maximum numbers in a sequence.

**Solution****. **

funmain(args:Array<String>) {// Calculation of two maximum numbers of a sequence a1, a2, ..., an// 1.Declare variablesvarmax1:Double = 0.0varmax2:Double = 0.0varn:Intvarnumber:Doublevari:IntvarfFirst:Boolean// 2. Input number n"n = ") n =readLine().toString().toInt()// 3. Loop for inputting numbers and calculating maximum valuesi = 0do{"number = ") number =readLine().toString().toDouble()if(i==0) { max1 = number max2 = number }else if(i==1) {if(max1<number) max1=numberelsemax2=number }else{if(max1<number) { max2 = max1 max1 = number }else if(max2<number) max2 = number } i++ }while(i<n)// 4. Print the resultprintln("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****. **

funmain(args:Array<String>) {// Formation of the Fibonacci series // 1.Declare variablesvarx1:Intvarx2:Intvarx3:Intvaln:Intvari:Int// 2.Input number n"n = ") n =readLine().toString().toInt()// 3. Checking n for correctnessif(n<3) {println("Incorrect input.")return}// 3. Setting initial values 0, 1 and outputting themx1=0 x2=1" ")" ")// 4. The cycle of the formation of a series and its outputi=2do{ x3=x1+x2" ") 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

- Loop for. Ways of implementation. Applying a for loop to ranges, arrays, lists, dictionaries, sets
- Ranges (intervals). Operator
**..**. Interval types IntRange, CharRange, LongRange

### ⇑