A loop allows a program to repeat a block of code either a predefined number of times or until some condition is met. Learn how to write a while loop, do/while loop, for loop and for comprehension in this video. Also learn when to choose each type of loop.
- [Instructor] Let's take a look at the syntax required to create a loop in Scala. A loop is a term that we use to describe code that executes a block of statements enclosed in curly brackets that is automatically repeated while some condition is true. Here's the syntax for a while loop. So while some condition evaluates to true, you're going to execute the block of code in curly brackets. The idea is that a loop allows us to control the number of iterations, where iterations just means the number of times we're going to execute that code in curly brackets.
Scala also has a variation on the while loop called the do/while loop. The only difference is the do/while loop executes at least once, so it's a good loop if you want to present your user with a menu and let them choose. So this looks like do, open curly bracket, our code that should be repeated, close curly bracket, while the expression is true. For both of these loops, it's really important that eventually something changes the condition to false so that the loop will end.
Otherwise, we have something called an infinite loop. Next, we have a for loop. The for loop looks like this: keyword for, open parenthesis, any variable name, I just chose i, but you could have put x, or you could have put in a word, maybe num, and then we have this symbol. It looks like an arrow facing the left, and it goes from one to 10, and then there's the block of code that will get executed. That block of code in this situation will execute 10 times because i will start at one, it'll at one each time, and it'll go through until it gets to 10.
So, it'll execute 10 times. So we use a for loop when we know ahead of time how many iterations are required for our task. And there is a variation of the for loop also, called a for comprehension. The for comprehension constructs a collection of values using the keyword yield. That's how you'll know it's a comprehension loop instead of just a regular for loop. The result of this type of loop is either a list or an array or a vector or a tuple or some other type of collection.
Let's switch over to the IDE and take a look at some programs in practice. I'm using the Scala IDE for Eclipse, and I'm going to start. I already have a worksheet example project, so I'm going to start by adding a worksheet to my source package, and I'm going to call it loopsPractice. Let's start with a while loop. So at the very top of our program, I'm going to get rid of the statement that says, println("Welcome to the Scala worksheet"), and I'm going to add a variable.
I'm going to say variable x is equal to 10. The goal of my loop is to print out the numbers from 10 to zero and then print out the keyword BlastOff! So if I start the variable x at 10, how do I get to the next value that I want to print? If you said you want to subtract one each time, you're absolutely correct. So our while loop is going to continue while the expression is true. So let's think about what that expression should look like. I want to continue while x is still greater than or equal to zero, but as soon as x gets less than zero, it will stop.
It'll get out of the loop. And then I'm going to do my open curly bracket for my code, and inside my code, the only thing I want to do for this simple example is to print out the number. So I'm going to print out 10, then nine, et cetera. So let me end the loop, and then I'm going to print out the words BlastOff! Okay, I don't have any errors, but there is a logic error. A logic error is an error that usually is only caught during runtime.
So let's run this. I'm going to save it, and it'll automatically run, and see if you can tell me what my error is. Well, you see the message in the bottom right-hand corner. Let me go ahead and minimize my package explorer so we can see more of the screen. And it says output exceeds cutoff limit. What happened was my loop kept going. So let's go back over. I'm going to have to cancel out of this, so I don't want to save my changes. Here we go. So now I'm back into my program, and the problem is that I've never changed the value of x, so my condition never goes to false.
So what I want to do is I want to say that x is equal to x - 1 each time, and now, I'll save it, and we'll see we should get the values 10 through zero and BlastOff! That works. I do want to point out that we can also do a shortcut here. We could have made this x -= 1. Some people prefer these types of shortcuts. Other people would rather see it spelled out, but both of those will work. So I'm going to just going to do this, 'cause it's the same as x = x - 1.
Right now, let's do the same thing, but let's do it with the do/while loop. So what I'm going to do is I'm just going to comment out my while loop here. I'm going to use a multi-line comment by using /**/, and now I'm going to do the do/while. So remember, do/while will always execute at least once. So I keyword do, open curly bracket, and I want to print out x the same way I did there. I still want to subtract one from x each time, and that's the end of the loop, and now what I need to do is provide my condition.
So while x is greater than or equal to zero, I'm going to continue my do/while loop. Once that changes to false, it'll come out, and it'll go down to line 20, and it'll print out the BlastOff! message. So let's save this, and we'll basically see the same thing, 10 to zero and BlastOff! Finally, let's do the same thing with the for loop, so we can see the syntax for the for loop. I'll add the */ down here, and now my for loop, this time, I still want to have the values go from 10 to zero.
Now, the difference here is when I'm using a for loop and I want to go backwards, I have to tell it how to do that. So I'm going to say I want you to go by negative one, by negative one, and then I'm going to add a println. And I'm going to print out x, and this time, I don't need to do the x -= 1. That's all taken care of in the one for statement, so it automatically will go from 10 to nine all the way down to zero, and once it gets down to zero, it's done. All right, let's go ahead and save this one, and we should see the same results, and we do.
So those are the three loops, the while loop, the do/while loop, and the for loop. Let's take a look at a for comprehension loop. So, I'm going to comment this out again. This time, I'm going to delete some of the space here, because I want to be able to get rid of the BlastOff! as well. So I'm going to do */, and now, I just want to show you how to do a for comprehension loop. It's going to look a lot like the for loop. So we have for, let's do num, and let's make the values of num go from one to 10, and the keyword I need to add here is yield.
So let's yield and say yield, we're going to do num + 1, and that's going to create a list of numbers that starts with one but then adds one. So it'll actually start with two, and it'll apply the num + 1 expression to every value from one to 10. Let's save that. And we can see, if I scroll over a little bit on the right-hand side, it created a vector that goes from two to 11, which is what we would expect. And I could even assign this to a variable. So I could even say var, and let's just say y is equal to, and now y will be a vector that has all those values.
So I can click save, and you can see, over on the right-hand side, y is a collection of variables. It's a vector of integers, and the integers go from two to 11. All right, let's take a look at another way to use these loops. The for loop is also the loop that you want to use when you want to process all the values in a collection, maybe all the values in a list. What I'm going to do is take a look at processing all the letters in a word. The same concept.
So I'm going to start by creating a variable called word, and I'll set it equal to Monday. Now, I would like to print out each letter on a separate line. So I'm going to go ahead and create a for loop, and I'm going to say that the loop is going to start with a value of x. I need my arrow to say that I want to start at position zero. When you're dealing with collections, the very first value always starts at position zero. They call it the index value. So the index value of zero for the word Monday has the value M, and this time, what I'm going to do is I'm going to use the word until, and I want to go until I get to the end of my word.
So I want to keep going until I get to word.length. Now, the until keyword will actually stop one before the value. So if we count the letters in Monday, so, one, two, three, four, five, six, word.length is going to automatically have the value six, but remember, my M is at position zero, so that means my y is at position five. So if I try and access position six, it's going to give me an out of bounds error. So the keyword until is used when you don't want to include that value.
You don't want to include the upper bound. All right, and in here, I'm just going to go ahead and print out, I'm going to use a println statement, and I'm going to print out word, but I want to print out word at position x. So that will allow me to print out the letter M on one line, the letter o. So in order to access values in a list, we could use the parenthesis, and we could use the index value. In this case, I'm starting with zero and going 'til five. So let me save this. And we can see on the bottom there on the right-hand side we have Monday, one letter on each line.
So this is the syntax for the while loop, the do/while loop, the for loop, and the for loop that includes yield. So one thing you want to be aware of is to be careful of an infinite loop, which occurs when the condition in a while or do/while never changes, or if, in your for loop, you do not set it up correctly, and it does not have an end.
Join Peggy Fisher as she helps get you started with Scala, so you can leverage the unique capabilities it offers. First, learn the basics of type inference, variables, loops, functions, and operators. Then, find out how to read files using a console, perform pattern matching, handle exceptions, and more. Finally, learn how to use classes, fields, methods, and objects.
- Integrating with IDEs
- Scala worksheets
- Scala repl sessions
- Type inference
- Creating variables
- Working with loops
- Higher-order functions
- Scala operators
- Working with decision statements
- Handling exceptions using try or catch
- Working with tuples and arrays
- Classes, fields, and methods