Contents

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

The course is part of this learning path

For and forEach Loops
Overview
Difficulty
Intermediate
Duration
34m
Students
13
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

Hello friends. If you're here watching this video, that means you've made it to the other side. That's cool.

In this video we're going to learn the For Loop. So, in computer programming, a loop is basically a sequence of instructions that is continually repeated until a certain condition gets reached. So, when we need to execute a block of code several times, we'll use looping statements. So let's just go in order here. We're going to first learn how to use the for loop in common programming language. The for loop, of course, is a control flow statement that iterates a part of the programs multiple times. So, the general form of the for statement can be expressed as you see here in the slide. Here we see the use of the range to method and the in operator, which we learned in our previous lessons. Yes, we did.

So, this is pretty much how the for loop gets used in general. Here, the i actually represents a variable. And when the program runs, each value in the defined range is passed to the variable i in turn. Then as a result of each transfer operation, the code defined in the loop runs. So now, we got that out of the way. You see this for loop execution flow on the slide? Here, the first step in for loop, the initialization part only executes once. The second step, the range in the for loop is evaluated on each iteration with the in operator, and that way if the range is not over, then the loop body gets executed. If the range is over, statements in the loop body do not get executed and control gets transferred to the next statement in the program after the for loop.

So, let's open Android Studio, we're going to do some fun practice here. I'll show you. First off I want to create a new Kotlin File, so I'll right click on the project package folder and I'll choose 'New', 'Kotlin Class/File' and then I'll choose the 'File' option and set the name of the file to be ForLoops, and let's create the main method. We're going to try to understand the for loop with a few simple examples. So, first let's print the numbers from 1 to 10 to the console. I'm writing the for here, I'll select the for statement suggested by the editor and press 'Enter'. Now, let's write a variable name inside parenthesis. You can write anything that you want to here, I am just typing number, and then I'll write the in operator, and finally, since we'll print numbers from 1 to 10, I'll write 1..10. That's when the program runs. Well, all numbers from 1 to 10 will be transferred to the variable in order.

So, of course we must define the operations that will need to be performed when each transfer operation takes place. For that I just create { } here and press 'Enter'. So, we also set the scope of the for loop. Now, let's print each element from 1 to 10 to the console. For this, what do I type? sout, press 'Enter' and I'll write number in parenthesis because numbers from 1 to 10 will be transferred to the number respectively. We will print this number variable to the console every time. Alright, so looks set, let's run the code. In the console, we should see the numbers 1 to 10, and there you go. So, obviously it's an easy example but we have now printed the numbers from 1 to 10 on the console. So, why don't we do another example? Let's see if we can heat it up a bit. We'll print the numbers from 0 to 5 and sum of these numbers to the console. That would be the sum of these numbers. Anyway, I'm converting the code here to the comment line. Okay, so now, I will create a variable called sum and type integer. The initial value of this variable will be 0. Now, let's create the for loop. So, I'll write for(x in 0 . . 5). We'll define the scope of the for loop with { }. Now, I want to print the numbers from 0 to 5 to the console, so I write x in parenthesis. Now, let's transfer the sum of the numbers from 0 to 5 to the sum. So, for this I'll write sum += x. If you remember, this expression will add sum and x and pass a result back to the sum variable. See how that works? But let me break it down a little bit here. Since the initial values of sum and x are zero, the initial value of the sum variable will be zero. Then when the loop runs again, the new value of x will be 1. So, first the number 1 will be printed to the console, then sum and x, that is 0 and 1 will be added and transferred to the sum variable. So, the new value of the sum is now 1. The loop will run once again and the value of x will be 2, and then 2 will be printed to the console, then sum and x, that is 1 and 2 will be added and passed to the sum variable, and as a result the new value of the sum variable will be 3. And then the loop will continue to run like this. You see where this is going, pretty cool though.

Now, outside of the for loop, let's print the sum variable to the console. So, I'll write '"Sum of numbers"' in parenthesis and now I'll write the variable sum after the $. Now, let's run our code. So, as you can see we first printed the numbers from 0 to 5 in the console and then the sum of the numbers from 0 to 5.

So, I do want to do another example to reinforce this concept of the for loop. This time though, we're going to print the even numbers from 0 to 10 and the sum of these numbers to the console. For this, I'll just copy these codes that we wrote here and I'll paste them here. Now, I just want to convert these code to the comment line. First I'll set the last value of the range to 10. Now, if you remember we were dividing by two to find out if the number was even and if the remainder is zero then we know it's an even number. So, for this we will use the if statement here; if(x % 2 == 0), the x is an even number. So, I'll cut the print method and the codes that we wrote for the sum operation here and paste it into the if block. Okay, so that's it. Finally I'll write even in here. Follow? So now, let's run and test our code. And there as you can see, the even numbers from 0 to 10 and sum of these numbers are printed on the console.

So, that's just a few quick examples of how the for loop is used and how I'm sure it kind of triggers what you could do with it. So, what we're going to do is learn how to use this for loop with arrays. I'm sure you remember when we were learning about arrays, when we were printing the elements of an array to the console, we used a separate print method for each element. So, if our array is an array of thousand elements, do the math, you're not going to sit there and write out a thousand different print methods. Of course not, there's got to be a better way, this is a computer for goodness sake. So, in that case, we can use the for loop. Why don't we just do a quick example right away?

So, I will convert the codes here to the comment line. Now, let's create a new array. First we will need to determine the name of the array, so here I'll just write myNumberArray. Now, after the =, I'll write arrayListOf and let the type of the array be integer. Now, let's determine the elements of this array. Let the elements of the array be (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). And now, the array is ready. Now we can print the elements of this array to the console using the for loop. So, after typing y in this parenthesis, this time we will write the name of the array instead of the range. Thus, each element in the array will be transferred to the variable y respectively, you follow that. So, now let's print the y variable, that is the elements of the array, to the console. So, I type sout and press 'Enter' and write y in parenthesis. All right. So, let's run our code. There you go. So, we've easily printed out all the elements of the array of the console. That's very useful. However, let's see how we can access the index numbers of the elements in the array. So, you could actually use a couple of different methods for this. First I am just going to copy and paste the code here and convert these codes with comment line. Okay? So, to find out the index numbers in the array, we can create a range here from 0-1 less than the array size. Why would we do that? You remember, index numbers always start from zero. So, that means, that the last index number will be one less than the array size. All right. So, the size of the array is 10. And index number is from 0-9. Therefore, numbers from 0-9 will be transferred into the y variable respectively. Now, let's print the elements of the array to the console using this index number. So, I'll write myNumberArray, and I'll open square brackets, write the y after the $ sign.

Now this expression will allow us to see the index number of the array in the console. So, let's print the elements of the array. So, after typing = using $ sign and curly brackets, myNumberArray, and inside the square brackets, I'll write y. All right. So, let's run our code. And there you go. That prints the index numbers of the array and which element is in which index, right there in the console. So, now let's try to access the index numbers with a different method. All right. So, well first, we'll write myNumberArray.indices here. And you know what? We're even going to turn these codes into comment line again. So, let's copy and paste these codes again. And since, I will share these codes with you, it definitely would be useful to see them all here. That's why I am doing this. So, all you have to do is write the name of our array here, that is myNumberArray, and use the .indices method. That way we can directly access the index numbers of the elements in the array. So, let's run the code one more time. And there you can see we have now printed the arrays elements and index numbers to the console. Now, is there a difference between these two ways to do it?

No. You can just choose whichever one is easier for you. So finally, I want to talk to you about this forEach. Because it's another loop and it's called forEach. And it's defined in Kotlin programming language. In fact, the work of this loop is almost the same as the for loop. But to me, I kind of think of it as just far more practical. So, you can print the elements of the array here to the console much more easily just by using the for each loop. So, without any further ado, let's learn how to use the for each loop, and then I won't be holding it out on you any longer. So, first I'll just copy and paste the array here. And now let's turn these codes into the comment line. Okay. So, now let's print the elements of the array named myNumberArray to the console using the forEach loop.

So, first I'll write the name of the array, that is myNumberArray. Then I'll write .forEach. I choose the for each as suggested by the code editor. And finally, I'll write the printIn method and I'll write it in parentheses. So, here the it is a variable, defined by this Kotlin programming language. And it represents each element in our array. So, now let's run and test it. All right. So, see we have now printed all the elements of the array to the console. Pretty cool. So, anyway, that's how the for each loop gets used. But we mostly use the for loop in our projects going forward here.

Although the for each loop is very simple to use, the for loop is often preferred by programmers because it just gives you a little bit more flexibility when you're working. Especially when you're working in groups or teams. All right, my friends. So, that's about it. We've learned about the different uses of the for loop. So, why don't we just take a short break here, and in the next video, we're going to learn about the while loop, and it's got nothing to do with coyotes. All right. See you next time.

 

About the Author
Students
170
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