Tanvir Hasan
Tanvir Hasan

Reputation: 23

Getting Lowest Number from the Standard Input (Explain the Code)

Can someone explain how this code below get lowest number from the standard input.

`fun main() {
    val n = readLine()!!.toInt()
    var min = Int.MAX_VALUE
    repeat(n) {
        val next = readLine()!!.toInt()
        if (next < min) min = next
    }
    print(min)
}`

Upvotes: 0

Views: 160

Answers (2)

Karunesh Palekar
Karunesh Palekar

Reputation: 2345

In the first step of function main() , The input is taken and stored in variable n .

 val n = readLine()!!.toInt()

Here n is the variable wherein the input is stored , which is in the form of integer after the .toInt() conversions

In the second step :

var min = Int.MAX_VALUE

Max value is stored in the min variable , The max value is supposedly 2147483647(when performed on Kotlin Playground).

In the third step :

repeat(n) {
        val next = readLine()!!.toInt()
        if (next < min) min = next
    }

A loop is created , which will go on until the size of variable n and each time in the loop , It will ask you for an input and if the input which is provided if that is less than the value in the min variable , then the value in the min variable will get replaced with the last input you provided .

In step four : The output is provided

 print(min)

Lets consider a scenario : If the value of n entered was 2 then , in the repeat block :

For n = 1 ,

At the end of the loop , you will be provided with the least value . You will be asked for an input , Consider input as 100 . Then 100 will be stored in next variable and since 100 is less than 2147483647(the value in the min variable) it will swap the value in the min with value 100 .

For n=2 ,

Now , once again you will be asked for input since the value of n is 2 : Now Consider the value entered was 50 , Since 50 is less than 100 (current value of min) , the value of min will now be 50 . And since the loop has been iterated for n times , the answer which is the value stored in variable min , as per the scenario 50 will be outputted

Upvotes: 0

Cl&#233;ment Perroud
Cl&#233;ment Perroud

Reputation: 533

First,

It asked you the number of int (n) you want to test.

It creates a min value that is the higher int value possible. (This will be useful next : because whatever your next input is, it will be inferior to the higher int)

Then, it creates a loop that will ask you n times to input a number.

Every time that you enter a new value inferior to the min variable, it replaces the min variable by your new value.

This way, the min variable will always be the minimal value of yours inputs.

Upvotes: 1

Related Questions