[MUSIC] Sometimes during the iteration for loop or a while loop, after some of the iterations are done, the rest of them should just be skipped. Let's look at an example of this situation and some code that takes care of it. The code is in the file named BreakExamples over here. And it looks a little different from files that you've seen before. First of all, there's no function keyword in the files, so it's a script. But also, this script, unlike the other scripts we've seen in this course, is divided into sections. Here, let me give a little more room. I think I'll just clear the screen here, there. This is a section, this is a section, this a section, so on. A section is a set of lines that begins with two successive percent signs. The section ends when another section begins, or at the end of the file, like this one. You'll remember that the percent sign signifies that it and the text that follows it on the same line are part of a comment, which is there only for humans to read. MATLAB colors a comment green. When there are two percent signs in a row, it means that a new section is beginning. MATLAB indicates that there's something special about that with a bold font. This font and this font is bold compared to that one. The significance of sections is that each section can be run by itself, as if it were the only thing in the script. You do that using special buttons on the editor. They're up here, we'll look at them in just a minute, but first, let's look at the first section of this script. Not this one, actually, the second section, which has a while loop in it. It sets all the values in the vector named readings, this vector here, equal to 0 until it's reached the first value that exceeds 100. The condition here in the while loop makes this happen with two parts. The first part here before the && allows the loop to continue only while the index is not greater than the length of readings. And the second part allows it to continue only while the readings are less than or equal to 100. You may remember that a major difference between a script and a function is that a script has no arguments. And it has no local variables. It uses the variables in the command window workspace. Since the script here readings the variable readings, we need to give readings a value. Let's give it a row vector of 20 random integers. And we'll reset the random number generator first so we can regenerate the same set of pseudorandom numbers for the next two examples. And so that you can easily repeat these exercise with the same results. I've generated numbers ranging from 1 to 105 here. Want to get at least some numbers above 100, and I see I've got some here. First one appears to be on one, two, three, four, five, six, seven, eight, at element nine. Now let's run example 1. I click anywhere inside this section, and when I click in that section, it's highlighted in yellow. Then I come up here to the ribbon, and I click the small green arrow with the tiny yellow page of text behind it here that says, Run Section. Well, it didn't seem like anything happened, but let's take a look at readings. Aha, we can see that the one, two, three, four, five, six, seven, first eight elements are now 0. And nothing has happened beyond there, because, over here the while loop got to element nine, realized it wasn't less than or equal to 100, so it skipped the rest of the reiterations. It did the first eight iterations, skipped all the rest of them, which is what we wanted it to do. Well, this works fine, but the condition of the while loop seems a bit cumbersome for all of this here. Or at least let's call it cumbersome, to give us an excuse to show you another way to do this. Example 2 provides another way. Let me highlight it. First of all, it uses a for loop instead of a while loop, which you can see here. Its control statement easily enforces the requirement that the index stay within the range of indices of the vector readings, but there's no possibility for the control statement of any for loop to check any condition whatever, the way there is with a control statement in the while loop up here. So it seems at this point that the loop will scan all the elements. The body of this for loop contains just one if-else statement. That statement checks the value of element ii of readings here to see if it's greater than zero. If it is, it executes this break statement. Otherwise, it sets the element equal to 0. The word break here is highlighted in blue because it's a MATLAB keyword. And this same keyword is used in the same way in many other languages. It's not the same thing as a breakpoint, these things we've set and we click up here and make a red circle to tell the debugger to stop on a given line. No, this break statement is an executable statement that causes the loop to end immediately. And it works for both while loops and for loops, and it's a more powerful mechanism for ending a loop than a while condition, because in addition to skipping the subsequent iterations, it can skip the rest of the statements in the current iteration. Here, for example, there could be more statements after this if-else statement, and every one of them would be skipped, if this break statement were executed. In short, the loop quits as soon as that break statement is executed, regardless of where it occurs in the loop body. Let's try this example. First we give our vector readings the same pseudorandom number sequence as before. Let's see if I can find that there. And now we click anywhere inside the next section of code. This one's example 2, last time we did example 1. And we hit the Run Section button again. Well, let's see if it worked. We have to look at readings. And it looks like it worked again. All these values before 101, which were originally less than 100, are now set to 0. And the rest have been untouched. Well, let's go over, one more time, how it worked. We enter the for loop, and it appears that we're gonna process each element of the vector because of the phrase, ii = 1:length(readings). That doesn't happen. As long as this if statement finds that the value of element ii of readings is not greater than 100, then the else clause dutifully sets that element to 0. When the if-else statement finds that the value is greater than 100, it enters the if clause and hits the break right here, which ends the loop immediately. By the way, the break statement can appear only inside a loop. In fact, MATLAB will stop the program and print an error message if it encounters a break anywhere that's not inside a loop. Okay, both these examples work and we've got another example. It also uses the break statement, as you can see here, but it takes advantage of MATLAB's answer to an age-old question in programming languages. When the loop ends, what happens to the for loop index? Well, in most languages, and MATLAB is one of them, it's still there. And it keeps the last value it had while the loop was executing. And that's true whether the for loop ended normally or ended with a break, and whether it was set by the for loop control statement or by a statement inside the body, etc. Occasionally, we can take advantage of the fact that the loop index keeps its last value. For example, suppose the problem is simply to find the first index with a value greater than 100, without setting smaller values equal to 0. Example 3 was designed to do just that. It starts out with the apparent intention of scanning through all the elements of readings with ii=1:length(readings). In its body is an if statement, though, and it uses a break statement to exit the loop at the first element that's greater than 100. After the loop comes this fprintf statement, which tells us the index of the first reading above 100. Looks pretty good, let's try it. We'll generate the same values once again. You recognize them by now, and we click in the last section and then click the Run Section button to run the code. And over here we see it says first reading above 100 is at index 9, and that's correct. This seems to work well, but there's a bug lurking in this code. Can you see it? It'll give the wrong answer in many cases. Let's try one of those cases. You just need to give it values that are all less than or equal to 100. There. Now let's run it again. Hm, it seems to think that the last element is greater than 100, but it's not. Well, let me see if I can figure out the problem. Gosh, I'm kinda tired though. Hey, I know what, I'll let you fix it. It'll be good exercise for you to exterminate this bug, and since you're gonna take care of that, we're done with our little script and its sections. I got to show you one feature of scripts with sections that is quite cool. Let's go up here to the ribbon and click on the tab labeled Publish here. There are lots of things you can do here. Now, I'm gonna show you just one. Let's click this button labeled Publish. And what shows up is a webpage version of your script, with fancy typesetting and layouts and links and so on. Let's compare the two. Here we have the top label, I call it a title, it's been put in red, nice large type. The version of MATLAB you have may vary this a little bit. This is the latest version as I'm speaking here. And then, there are these sections here, each one of those is put inside this thing called Contents. And if we click on these, we see their links, like there's Example 1. We click there. We're on Example 1. You can see the code. Here's the comment I've got on Example 2, Skipping is accomplished with a break statement. Let's go to Example 3 down here. Shows that the for loop index looks very professional. It even runs each one of these. There was no output with the first two, but this one has output. First reading above above 100 is at index 20. Hm, well, that reminds me, that bug is still there. You haven't fixed it yet. Maybe we don't wanna show this, but if we did, you can link it into other web pages, you can email it, you can show it to your friends. I think that's quite cool. And by the way, this web page is stored in a little folder inside the current folder that's generated by Publish. If you go in here you can see BreakExamples, which is the name of this M file, .html. Let's go back up to where we were before. Okay, now, what were we talking about? Oh yes, you were gonna get rid of that embarrassing bug that we discovered when we ran this third example. And speaking of bugs, there's an extremely common bug that shows up when break statements are used in nested loops. It's a big problem for novice programmers, not that being a novice programmer is like a bad thing. Many of my favorite people over the years have been novice programmers. I used to be a novice programmer myself. But the fact remains that novice programmers have trouble with this problem. The problem is that the break statement breaks out of only the innermost loop, meaning that it will cause the loop that appears in to terminate but the outer loop will continue. That is often not what the new programmer expects. We're gonna look at an example that works with a two-dimensional array. So, let's generate one. There is a nice array. We want to look at each element in row major order. That's first row, then second row, and so on. And set the elements equal to zero, until we find the first value that's greater than 90. We want to leave that element and all the other elements after it as they are. So in this case, we wanna put all zeroes on this first row, because there's nothing greater than 90 there. And we move to the second row, and we put zero here and here. But when we get to the 97, we stop, we don't put a zero there. And we leave everything else as it is and we're done. This is a job for, for loops, and since we want to be able to stop before we get to the end, but we can't know where we want to stop until we get there, it's also a job for the break statement. Here's our first try in this file called BadBreak. As you can see, there's a for loop here, it's index, ii, goes from one to the size of (A,1). Size of (A,1) means the first dimension of A, which is the number of rows. Then there's an inner loop, whose index, jj, goes from one to the size of (A,2). Size of (A,2) returns the second dimension of A, which is the number of columns. So, ii set equal to one, and we go in here, and jj goes from one to eight, because there are eight columns in A, and it checks the values of the elements, ii, jj against 90. And if they're less than or equal to 90, it sets them to zero, or else it breaks. Well, that looks pretty good. Let's try it. We can run it by typing it's name, we can also run it by clicking on Run, up here. That works well for script, so let's do that. So BadBreak ran and let's take a look at A. Something's wrong. We should have set the first row equal to zeros, we did that. Then we should have set these two equal to zero, we did that, and stopped with the 97, and it looks like we're stopped, but then we seem to start up again on the third row. Two more zeroes. And wait a minute, this 63 here got set to zero, too. This is exactly the problem we were talking about. The break statement stopped the inner loop, not the outer loop. Well, this example is just complicated enough to warrant the debugger. First, I'm gonna clear the command window because I want to print some things in there. And then I'm gonna set A back to the value it had before. There. Okay, I'm gonna set a break point, but before I do, I'm gonna remove the semicolon here after this zero, because I want A to print out. And I want it to print out each time through the inner loop. And that will make it do it. Now, I'm ready to set a break point. I'm gonna put it right here at the beginning. Oops, it's gray, that means that I have to save this. It means that the file that I'm breaking, it's not the same file that I'm looking at here. Okay, we're ready. Let's run it. I'm gonna click Run and we see that BadBreak has run. The K means we're in the break system, and so this little green arrow, which points to the next statement that's gonna be executed. We haven't done anything yet. We're about to enter the outer loop, so I'm gonna take one step, when I do this, you see that little hint there that shows you, depending on your operating system, a shortcut you can use for this on the keyboard, I like to use the buttons, so I'm gonna do that. So we go in here and ii is set equal to one, if you hover over the ii, you can see it's value is one. Now we're about to enter the inner loop. Let's do that. Now we see that ii is still one, jj is one. And we're checking the value of A(ii,jj), which is (A1, 1), it's 81, it's less than or equal to 90. We'll set it equal to zero. And of course, it is. So we're gonna enter this if branch, and set this equal to zero. So, let's carry that out. And when we do, you'll see the whole array, A, printed out. That's what happens when you assign any value to an array, and leave the semicolon off the assignment statement. Not just the element that you assign, but the whole array prints out, and that's kind of nice for us here. We can see what the array looks like and we can see how it was changed from the last time. Just this zero showed up here. Okay, we're ready to complete that iteration of the inner loop. And now, here we are at the second iteration. The outer loop still has ii equal to one, the inner loop now has it at two. And we're about to check the element (1,2), which is also less than 90, and you can see it's set to zero. And we can continue in this way, going all the way through, the first row, and every single thing on that row gets set to zero. Now we've finished that row. And that puts us at the end of the inner loop, and we're down here at the end statement of the outer loop, and you know the end statement will cause the ii to take on it's next value, which is two. So, let's go forward one step. Okay, we're now back at the top. And we're about to enter the inner loop, again. This time, ii is equal to two. Be a little more careful here. So now we've entered that loop, ii is equal to two, jj is equal to one. So we're gonna be looking at this element right here, which is equal to 90, it is less than or equal to 90 because it's equal to 90, so we'll go into this branch again, there, we did, and we'll carry it out by setting that element equal to zero, let's do that. And it got set equal to zero, as you can see here. So we're at the end of that iteration. Let's take another step. Ii is still equal to two, we're still on the second row, jj is now equal to two, so we're looking at this element, it's 28. It'll be less than 90. So, we enter the if branch, we set it equal to zero, you saw it become zero there. Now let's take one more step. We've entered the third iteration of this inner loop. ii is equal to two. jj is equal to three. So we're about to look at this element. This element is not less than or equal to 90. It's 97. So we'll go to the else branch. There we are. We're about to execute the break statement. In the break statement, we were expecting to exit the whole thing, but it's only going to exit the inner loop. So let's watch that happen. There. We jump down, we're out of the inner loop. We've jumped down to the next iteration of the outer loop. ii is now equal to 3, so we're down here on the third row, now we see the problem. We needed to break out of the outer loop at the same time we broke out of the inner loop. We needed to break out of this loop, and we broke out of this loop with this break statement. Well, now we know what went wrong, so let's quit our debugging session. We can do that by clicking that great big red square here labeled Quit Debugging. There, debugging session is over, and one indication that it is, is there's no green arrow here. And another one is that we don't have k in front of our prompt anymore. We've established that we need to break out of the outer loop, as well as the inner loop when we find what we're looking for. So how do we do that? Well, we've got code here that does it in GoodBreak.m. Let's take a look at that. Well first, we see a new variable here called found. We set it equal to false before we even enter the outer loop. Then inside the inner loop down here, where we have the break, we set found equal to true before we execute the break. And then in the outer loop, after we're done with the inner loop, we check found to see if it's true. There are two versions of the conditional for checking the value of found, the first version is found double equals true, like this. That certainly checks to see if found is equal to true. And the second version is the one we've got here. Either case works, because in both cases the condition will be true if and only if found is equal to true. If found is true then we break out of the loop. We've already broken out of the inner loop right after we set found equal to true. And so we break out of the outer loop and we're done. The variable found, which shows up in three places typically, is called a flag. A flag usually has only a few values and most often just two values like this, true and false, the most common. And it serves as a signal that affects the behavior of the program. Here the behavior is to exit the outer loop or not. And the flag is the standard solution to the problem of exiting nested loops. There is another way, but it can only be used when A, the nested loop is inside a function, and B, it's appropriate to exit the function, when you exit the nested loops. You just replace this break in the inner loop with a return, and you can forget this part, and this part, And this part. In other words, you can forget all the breaks and all the flags. Return leaves the function for good, regardless of how many nested loops there are. If you have work to do in the function after the nested loops are done, then it's not appropriate to exit the function when you exit the nested loops, and it typically isn't appropriate. So you should remember how to use a flag. Well, let's get our nested loops back the way they were by doing a few of these undos. There. And with that, we're done with the break statement. But there is a related statement called the continue statement. It's similar to the break but instead of using the break keyword, you use the continue keyword. And instead of quitting the loop, it skips what's left of the current iteration of the loop, and moves to the next iteration. In a for loop index takes on its next value, and the next iteration begins. In a while loop, it just goes to the beginning and checks the loop condition again. But probably the biggest difference between the continue statement and the break statement is that the continue statement is just not used very much and the break statement is used a lot. So, we're not gonna cover the continue statement in this course. But if you're interested in it, check it out in the textbook. [MUSIC] [APPLAUSE]