Lesson 12: While Loop in Kotlin Language

Lesson 12: While Loop in Kotlin Language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

While Loop in Kotlin Language. So far we have used SEQUENTIAL and CONDITIONAL structures. There is another type of structures as important as the previous ones are LOOPING structures.

 A looping structure allows you to execute a statement or an instruction set several times.

A looping execution of sentences is characterized by:
– The sentence or sentences that are repeated.
– The test or test of condition before each repetition, that will motivate that the sentences are repeated or not.

While Looping structure in Kotlin Language.

Graphic representation of the while:

Lesson 12: While Loop in Kotlin Language - Lesson 12: While Loop in Kotlin Language - Lesson 12: While Loop in Kotlin Language - While Loop in Kotlin Language
While Loop in Kotlin Language

We must not confuse the graphical representation of the repetitive structure “while” with the conditional structure “if”

Operation: The condition is verified first, if it is true, the operations indicated by the branch of the True are executed.
To the branch of the true we plotted it at the bottom of the condition. A line at the end of the repetition block connects it to the top of the repetitive structure.
In case the condition is False, it continues through the False branch and leaves the repetitive structure to continue the execution of the algorithm.

The block repeats WHILE the condition is True.

Important: If the condition always returns true we are in the presence of an infinite repetitive cycle. This situation is a programming error, it will never end the program.

Problem 1

Perform a program that prints the numbers from 1 to 100 on the screen.

Project31 – coding180project.kt

fun main (parameter: Array <String>) {
//coding180.com
     var x = 1
     while (x <= 100) {
         println (x)
         x = x + 1
     }
 }

The first thing to note is that we define a mutable variable of type Int with the value 1:

     var x = 1

This variable x will be modified within the while so the need to define it with the keyword var.

The repetitive structure while always has a condition, if it is true, it happens to execute the block of instructions enclosed in braces (if there are no braces, just execute the next while statement in a similar way of if)

Each time the while statement block is executed, the condition is checked again to see if it repeats again or cuts the repetitive cycle.

In our problem x starts with the value 1, when the condition is executed TRUE because the contents of x (1) is less than or equal to 100. When the true condition executes the instruction block containing the while structure. The instruction block contains an output and an operation.

The contents of x are printed, and then the variable x is incremented by one.

The operation x = x + 1 is read as “in the variable x the contents of x plus 1 are saved”. That is, if x contains 1 after executing this operation will be stored in x a 2.

At the end of the instruction block containing the repetitive structure, the condition of the repetitive structure is checked again and the process explained above is repeated.

As long as the condition returns true, the instruction block is executed; When false return the verification of the condition leaves the repetitive structure and continues the algorithm, in this case the program ends.

The most difficult is the definition of the condition of the while structure and which block of instructions will be repeated. Note that if, for example, we have the condition x> = 100 (if x is greater than or equal to 100) it does not cause any syntactic error but we are in the presence of a logical error because when the condition is evaluated for the first time it returns false and Executes the block of instructions that we wanted to repeat 100 times.

There is no RECIPE to define a condition of a repetitive structure, but it is achieved with a continuous practice solving problems.

Problem 2

Write a program that asks for the loading of a positive value and shows us from 1 to the value entered one at a time.
Example: If we enter 30, the numbers 1 to 30 must be displayed.

Project32 – Home.kt

fun main (parameter: Array <String>) {
//coding180.com
     print ("Enter a value:")
     val value = readLine () !!. toInt ()
     var x = 1
// While Looping structure in Kotlin Language
     while (x <= value) {
         println (x)
         x = x + 1
     }
 }
Lesson 12: While Loop in Kotlin Language - Lesson 12: While Loop in Kotlin Language - Lesson 12: While Loop in Kotlin Language - While Loop in Kotlin Language
While Loop in Kotlin Language

The variable x is called COUNTER. A counter is a special type of variable that is incremented or decreased with constant values during program execution.

The x counter tells us at each moment the amount of values printed on the screen.

Problem 3

Develop a program that allows the loading of 10 values per keyboard and then show us the sum of the values entered and their average.

Project33 – Home.kt

fun main (parameter: Array <String>) {
//coding180.com
    var x = 1
    var sum = 0
    while (x <= 10) {
        print ("Enter a value:")
        val value = readLine () !!. toInt ()
        sum = sum + value
        x = x + 1
    }
// While Looping structure in Kotlin Language
    println ("The sum of the 10 values ​​entered is $sum")
    val average  = sum / 10
    println ("Average is $average")
}

In this problem, like the previous ones, we have a COUNTER called x that serves to count the laps that must repeat the while.
Also the concept of ACCUMULATOR appears (an accumulator is a special type of variable that increases or decreases with variable values during the execution of the program)

We have given the sum name to our accumulator. Each cycle that repeats the repetitive structure, the sum variable is incremented with the content entered in the value variable.

Problem 4

A plant that manufactures iron profiles has a batch of n pieces.
Make a program that asks to enter by keyboard the quantity of pieces to be processed and then enter the length of each profile; Knowing that the piece whose length is comprised in the range of 1.20 and 1.30 are apt. Print on screen the number of fit pieces in the lot.

Project34 – Principal.kt

fun main (parameter: Array <String>) {
//coding180.com 
// While Looping structure in Kotlin Language
    print ("How many pieces will process:")
    val n = readLine () !!. toInt ()
    var x = 1
    var quantity = 0
    while (x <= n) {
        print ("Enter the measurement of the part:")
        val long = readLine () !!. toDouble ()
        if (long >= 1.20 && long <= 1.30)
        quantity = quantity +1
        x = x + 1;
    }
    print ("The number of pieces eligible are: $quantity")
}

We can see that within a repetitive structure there may be conditional structures (there may even be other repetitive structures that we will see later)

In this problem, the number of pieces to be entered (n) must be initially loaded, then n length values of parts are loaded into the while.

Each time we enter a piece length (long) we check if it is a correct measurement (it must be between 1.20 and 1.30 the length to be correct), if it is correct, we COUNT (we increase the quantity variable by 1)

The quantity counter is initialized to zero because initially no measurement length has been loaded.

When we leave the repetitive structure because n lengths of pieces have been loaded, we display the quantity counter (which represents the number of suitable pieces)

In this problem we have two COUNTERS:

x (Count the number of pieces loaded so far)

quantity (Count the iron profiles fit)

Problems proposed

  • Write a program that asks you to enter 10 student grades and tell us how many have grades greater than or equal to 7 and how many grades.
  • A set of n heights of people are entered by keyboard (n is entered by keyboard). Show the average height of people.
  • In a company, employees are employed whose salaries range from $ 100 to $ 500, a program that reads the salaries of each employee and reports how many employees they charge between $ 100 and $ 300 and how many they charge more than $ 300. In addition the program must inform the amount that the company spends in salaries to the personnel.
  • Make a program that prints 25 terms from the series 11 – 22 – 33 – 44, etc. (No keyboard input)
  • Display the multiples of 8 up to the value 500. It should appear on screen 8 – 16 – 24, etc.
  • Perform a program that allows loading two lists of 5 values each. Report with a message which of the two lists has a higher accumulated value (messages “List 1 major”, “List 2 major”, “Lists equal”)
    Keep in mind that there may be two or more repetitive structures in an algorithm.
  • Develop a program that allows you to load n integers and then tell us how many values were even and odd.
    Use the “%” operator in the condition of the conditional structure:

    	 if (value% 2 == 0) // If the if statement is true then it is even.
    

Solution

 

About The Author

Related posts

Leave a Reply