While Loops and Infinite Loops

Contents

keyboard_tab
Loops in Kotlin
1
For and forEach Loops
PREVIEW16m 30s

The course is part of this learning path

While Loops and Infinite Loops
Overview
Difficulty
Intermediate
Duration
34m
Students
8
Ratings
5/5
starstarstarstarstar
Description

This course explores Kotlin loops, including for loops, forEach loops, while loops, infinite loops, and do-while loops.

Intended Audience

This course is ideal for anyone who wants to learn how to use Kotlin for developing applications on Android.

Prerequisites

This content will take you from a beginner to a proficient user of Kotlin and so no prior experience with the programming language is required. It would, however, be beneficial to have some development experience in general.

Transcript

Well, hello everyone. So, this is the video that we're going to learn about the while loop, not while loop, while loop just like the word. So, in the while loop, the controlling variable is previously defined. So, the condition is evaluated first and if it returns true then the statements in the loop body are executed. So, generally the loop body contains an update value for the variable being processed for the next iteration. If the condition returns false, the control comes out of the loop and jumps to the next statement after the while loop. So, let me show you a few examples using while loop. So first, let me just create a new Kotlin file and we'll call this file WhileLoop, see while. Now, let's create the main method. So, let's do our first example like this, we will print the numbers from five down to one on the console. So, for this operation, I'll just declare a variable i = 5 and now we'll create the while loop. So, I'm typing while here and look what our code editor suggests.

So, I'll just choose the while option and I'll write (i > 0). Because I want this loop to continue as long as the value of i > 0. So, we've created the condition, now let's define the scope of the while loop. We use {} for this and in this field I will define the action that I want to be done. So, we should print the value of i to the console every time the loop runs. So, for this I write sout, press 'Enter', and I write println(i). Also we'll need to update the variable i, so we decrease the value of i-- . So, let's run the code. And there you can see the numbers 5, 4, 3, 2 and 1 are printed on the console. So, after five iterations i will be zero, then our condition i  > 0 is evaluated to be false and the while loop terminates. So, why don't we write a program to calculate the factorial of the first five numbers? Well, first of all maybe we ought to clear up this factorial. You might have forgotten some of our friends out there might just be, well, I don't know, it's reminiscent of something. Anyway, the factorial of a number is obtained by multiplying the numbers from itself to one. For example, when calculating the factorial of three,

well you multiply 3 * 2 * 1, and we can say that the factorial of three is six. Or I'll give you another example when calculating the factorial of five, just multiply the numbers 5 * 4 * 3 * 2 * 1, and we can say the factorial of five is 120. So, there you go, that's factorial. Now, let's start coding. So, we'll declare two variables, first k = 1, the second fact = 1. Let's start the while loop with the condition k < 6. So, the loop will assign fact multiply k through the variable fact *= . So, if you remember this spelling means fact = fact * k. Yes, of course you do. So, why don't we print the value of k and fact variable by using this print method? So ("$k!"). Because remember in mathematics, the factorial is represented by ! . I remember when I was a kid I used to think it was an angry number. But anyway I'll just write = $fact. Now, we've also got to increase the value of k++. So, the loop will continue until the value of k is six. And each time the loop runs the factorial of k will be calculated and printed to the console. And then when the value of k becomes six, that loop will end. So, let's run the code. 1! = 1, 2! = 2,  3! = 6, 4! = 24, 5! = 120. So, you see that, that's how that works, that's cool, it gets kind of exciting. But that's why I want to bring up to the idea of infinite loops. Yes, there are such things as infinite loops. So just imagine, not a Mobius in this case, but in infinite loops, the loop continues just like it is until the desired condition is met. The loop only terminates when the desired condition is met. You see what that means, right? So, if you notice in the examples here that we've done so far, we've set a condition and continued the loop until this condition is met at very specific condition. We use increment or decrement operations for the end of the loop. But here we determine how long the loop would take, that's why it's here. So, what do you do then if you don't know how long the cycle is going to last? But obviously, you don't want to just continue forever and ever. Well, I'll just explain it with an example. How's that? So, let's say for example, you will develop a number, a number guess application. So in other words, the computer is going to generate a random number and the range that you specify and then you'll ask the user to guess this number. That's always fun.

So, if the user cannot guess the number randomly generated by the computer, well, they're constantly asked to enter a new guess. So, as long as the user doesn't guess the number correctly, well an infinite loop will continue. And then, if the user guesses a randomly generated number, the loop will terminate. So, then as a result we're going to want to run some code to run continuously, then we're going to use an infinite loop. So, infinite is only implied. So, why don't we do that simple number guess application because I think it's pretty fun anyway and it's simple to set up. And this way you will definitely be able to understand the concept of the infinite loop so much better. So first off, we'll need to generate a random number. For that we can use the class named Random in common. What do you think of that? So, I'll write Random. So, as you can see the editor offers a few different options called Random. So, from here I'll choose 'Random' which is a class from the Kotlin.random package represented by C. We'll press 'Enter', and then when you type .next, as you can see a lot of options appear. So, we can generate random numbers of the type integer, double, float. So here, I'll just choose the nextInt method. And finally, I've got to specify the range of the numbers to be generated. So for this, why don't we just generate a random number between 0 and 100? So, I'll just write 0, 100 here. So, generating a random number in Kotlin is pretty doggone easy. Don't you think my friends?

So now, we've got to transfer this randomly generated number to a variable. So, I'll write val number = at the beginning of this code. Thus, a random number between 0 and 100 will be generated and then passed to the variable number. So now, we have randomly generated number here, what are we going to do with it? Well, we're going to take the user's guess. So, first let's just deliver a message that informs the user. So, I'll write, ("Please enter a number"). Now, let's create our infinite while loop. So, after typing while, we've got to write an expression in () that will always be true. For example, we can write, 2 > 1 or we can write true. It's just it's enough that the expression that you write here is correct. It doesn't actually even matter, you can write anything you want as long as it's true. So for now, I'm just writing 2 > 1, we'll keep it simple. Now, let's take the user's guess, pass it to a variable. So here, I'll write val userGuess:Int = readLine()!! . toInt(). You see that? So, we can now evaluate the user's guess using the if else statement. If the user guess equals the number, let's message the user, "Hey man, congratulations, you know the number in my mind." Of course, if the user's guess is correct, the condition will be satisfied and then the loop is going to have to end. So, how would we end the loop in this case? Well, for this example it's enough to write the break keyword here. So, as soon as you type the break keyword, your loop will end. Now, let's create the other conditions. So here, I want to use the else if statement. If the users guess is less than the randomly generated number we can tell the user to increase their guess. And then finally in the else block, well we can use this to tell the user to decrease their guess. Because the last condition is that the users guess is greater than the randomly generated number. All right my friends, so we've created the infinite loop. This loop will indeed continue until the user guesses correctly. So, what do you say, we run it and test our code? So, there you go, there's an expression that tells us to enter a number in the console and we've got a value between 0-100 that's generated and passed to the variable number. And when we enter a guess, the guess will be compared with a variable number and I'm just going to type 50 as the first guess, press 'Enter'. So, you don't necessarily know the randomly generated number. So, we'll need to decrease our guess and for a second guess let's type 40, press 'Enter'. What do you know, I got it wrong again. This time I'll need to increase my guess. So, see we're getting somewhere so now I'll enter 41, need to increase it again, enter 42. What do you know?

I guess we have to animate some balloons or something, but not in this course. So, as you can see, the loop will continue until a correct guess is made, far out. So, when we guess correctly, that stops the loop. Unfortunately, you were kind of hoping that it was going to go on for at least a day or two. Well, it's only 0-100, anyway that's what you call an infinite loop. So, I hope you had fun with the concepts of while and infinite loop and you have a little better understanding anyway. So, we're going to take a short break here and next up in our next video, we're going to learn the do-while loop. I'll see you in the next video.

 

About the Author
Students
86
Courses
23
Learning Paths
1

Mehmet graduated from the Electrical & Electronics Engineering Department of the Turkish Military Academy in 2014 and then worked in the Turkish Armed Forces for four years. Later, he decided to become an instructor to share what he knew about programming with his students. He’s currently an Android instructor, is married, and has a daughter.

Covered Topics