This course explores the fundamental concepts and syntax associated with Control Flow and showcases these with some real-life projects.
Learning Objectives
- Learn about the three categories of control statements: sequential, selection, and repetition
- Manipulate control statements using the continue and break statements
- Learn about pseudo-random numbers and the Random class
Intended Audience
- Beginner coders or anyone new to Java
- Experienced Java programmers who want to maintain their Java knowledge
- Developers looking to upskill for a project or career change
- College students and anyone else studying Java
Prerequisites
This is a beginner-level course and can be taken by anyone with an interest in learning about Java.
So far, we have learned about sequential and selection control statements. We know that sequential control statements also called sequence control statements are the default in Java, and that within a given methods such as main, these statements are executed in the same order that they are written. There is no selection or repetition going on. In the previous lecture, we discussed selection control statements which use conditions to determine if certain blocks of code are executed. So, remember the three control statement categories?
Sequential, selection, and that's right, repetition. That is what this lecture is all about. Repetition control statements are also called loops. Statements in this category can repeat a block of code many times. There are three syntactical varieties of repetition control statements in Java which are: while loops, do while loops, and for loops. There's also a variation on the for loop called the enhanced for loop or the foreach loop, but we don't discuss that right here. It is a for loop but more of what we might call syntactic sugar, which means it's not 100% necessary but just makes our lives easier in some circumstances.
Let's create a file called RepetitionFun. So, if we go up to 'src' here, create a new Java class, call it RepetitionFun. And inside of here, I will create public static void main (String[] args), end main. Let's create a count here, count = 0, and we'll start with a while loop. So, while the count < 10 and then I put a little comment here so we know what's going on. And inside of here, I'm going to print out the count value. And we also have to make sure that the count changes in order to move toward this condition right here being false because if we don't it'll keep going forever and ever. So, the count starts at zero, but then each iteration of the loop, each time we go through the loop it will increase the count by one until it reaches 10 and breaks out of the loop. All right, so we're printing out the count each time and then incrementing. Let's run this and see what happens. All right, pretty cool.
So, it starts at zero which we expect because our count was initialized to zero. And then it tests each time through the loop, prints out the zero. Then increments to one, is one less than 10? Yes, it is. Is two less than 10? Yes, it is. etc, etc. Until it gets to nine. Now, Why doesn't print out 10? Well, when it prints out nine, the count increments to 10 goes up to the top and then this right here called the loop continuation condition, 10 less than 10, that's false. So, that means that that will stop, it terminates the loop, and then goes here and then ends the program. So, the while loop is what we call a pre-test loop, which means it performs the conditional test controlling entry and repetition of its associated code block before executing the code block.
With selection control the condition acts like a gatekeeper or guide that controls access to a block of code or directs the flow of control to different blocks of code. But with repetition control statements like while loops, this test controls if and for how long essentially the loop repeats. The condition again is called the loop continuation condition. So, as you can see the numbers that are printed out are probably what you expected. Notice, that if we hadn't put the count++ statement in the loop's body again the loop would technically go on forever because count would remain zero and zero is always less than 10.
If this were to have happened, we would have what is called an infinite loop. This is a logic error, it means that theoretically the loop would never end if left alone. But usually we or the operating system or the runtime environment will detect a long running process and kill it or ask us if we want to kill it. So, we want to definitely avoid infinite loops under almost all circumstances. The second loop that we'll look at is called a do while loop. This loop, unlike its brother the while loop, is a post-test loop, which means that it executes its body and then tests the loops continuation condition. So, the difference between while and do while was that do while loops are guaranteed to run at least once. Let's take a look at the syntax. So, I'm going to just temporarily, we're going to comment out this stuff, and I'll put a do while loop down here. Let's called it count2, and the do while loop looks like this, while we'll say count2 < 10 and there is a semicolon at the end, so that's one other difference, count2++. And then we'll say print out count2, and let's run it and see what happens.
And we essentially get the exact same thing. The behavior is essentially the same except it does the test after the body of the loop is executed. So, under normal circumstances it's going to behave exactly like this while loop. However, if the count variable has a value such that the loop continuation condition is false going into the loop. Let's see what happens. So, the condition was count2 < 10. So, if we make It let's say 15 to start with, it's going to be false going into the loop. And then, it's going to get incremented to 16 and then it will do the test. So, let's see what happens. When we run it, it now just prints out the 15. So, it does iterate once. The while loop would not in fact, it would be false immediately. So, it never go into the body of the loop, it still operates once, it's guaranteed to and that's because the do while loop again is post-test. Now, let's look at for loops. For loops like while loops are pre-test loops meaning they test their loop continuation condition before each iteration. I'm going to comment out our do while loop here, and again to remind you if you highlight a block of code and do control forward slash or command forward slash if you're on a Mac, that will toggle the comments.
So, you don't have to write them all manually or you could do a multiline comment, that would be fine too. So, for loop, now in this case, I'm going to use the variable name i, i < 10; i++, and then end of the for loop. In this case, System.out.println(i) and let's see what happens here. Right click, run it, and no surprise there. We get the exact same output that we had before. You just notice that we have a little bit of a different syntax going on here. So, the for loop can have the declarations, condition tests, and counter variable changes like incrementing, all in the header of the loop as opposed to doing all of this before the loop, and then in the header and then in the body. For loops have perfect syntax for when we have the loop controlled by a counter of some sort called a counter-controlled loop. Note also that by convention, the counter variables often are named with single character names like i, j, and k, but they can be any kind of valid identifier in Java like counter or my counter and things like that. It's one of the rare exceptions that developers will tolerate bad names. I really like categorizing things and learning categories and teaching categories because they help us to compartmentalize our knowledge and build on it carefully.
So, I pay a lot of attention to categories as you may have noticed. One way we categorize loops as you've already seen, is by whether they performed the loop continuation condition test before or after the code is executed with each iteration. That would be the pre-test and post-test loops. Another way again, is by whether the loop is counter-controlled, like we're seeing here or sentinel-controlled. What we've seen thus far has all been counter-controlled because each of the loops continuation conditions depend on a counter. The for loop is in fact made perfectly for counter-controlled repetition, but any of the loops can do it as we've seen. Likewise, while the for loop can do sentinel-controlled repetition, it's more common to do so with a while loop or a do while loop. So, let's take a quick look at a sentinel-controlled repetition scenario.
All right. So, we will comment out this for loop and let's write a while loop. So, actually I need to have a scanner so I'm going to do that at the top of the loop. In fact, I think I'm going to put everything up here. So, Scanner keyboard = new Scanner based on (System.in). And we will import the scanner, of course, to make it easy to access. And we want to let's say have an integer, we'll say, input and then here's how it's going to work. We will write the while loop so that it keeps printing the numbers that are input, it will keep echoing the number is what we would say that the user inputs, as long as the integer is non-negative. As soon as, we hit a negative value, the loop will stop. So, let's write this while loop in just a second. Let's first do what's called a priming read. So, priming read will set us up to get the while loop ready, the loop ready. We'll say, ("Enter a non-negative integer"). So, that would be zero or higher or negative to exit is what we'll say, and then we'll say input = keyboard.nextInt(); grab that integer. And then while, that input integer, is greater than or equal to zero, we will keep looping and keep printing.
So, since we took in the input before the loop with the priming read, we're going to print out that value right here. Print out the input and then ask for it again. So, I could actually in this case, even though normally we try to avoid copying and pasting and here it probably makes some sense, right there. So, as long as the user is entering non-negative values, it will obtain the value and then print it. Since we're not obtaining strings or anything like that, we don't have to consume the new line character so we should be okay. And then after the loop just to maybe do a proof that we're outside the loop we'll say, ("Done!"), like that. Let's see what happens when we run our application here.
So, we run this. It says enter a non-negative integer or negative to exit, we'll say 100 and it echoes 100, 150 echoes 150. Bring that up a little bit here, and let's say 22 and it echoes 22. And then what we're going to do is we'll enter a negative five and then it says done. So, that's pretty cool. The sentinel value or in this case sentinel values is any negative integer or range of negative integers because that causes the loop to end. So, as a quick challenge for you, I want you to create a new Java file called SumFun, like S-U-M-F-U-N. And I want you to do a priming read like we did here, and as long as the user enters a non-negative integer, I want you to add the value to a sum that you maintain and then as soon as they enter a negative integer, it shouldn't put that into the sum and it breaks out of the loop and then you should print the sum. So, it's very similar to what we did here, but you'll have to really put your thinking cap on. So, pause the video and come back when you're done or if you need some help.
How did that challenge go for you? Were you able to complete it? If not, don't worry, you'll get better. This one's a little tricky like I said. Let's do it together, and then you can be more confident about how it works. So, we're going to close this file that we had opened. Right click 'src', 'New', 'Java Class'. Make SumFun right here. Public static void main(String [ ] args) { }//end main. Here we go. And now we have to declare and initialize some variables to help us. So, we'll have to keep track of a sum, that's for sure and also an int input. And we of course have to have a Scanner. So, Scanner keyboard = new Scanner(System.in) and we, of course, have to import our keyboard or our Scanner rather not remove local variable; don't want to do that. Import class. Here we go. And it imports java.util.Scanner. So, now we can take input. We'll do a priming read and prompt the user for the input.
We'll say, ("Enter non-negative to add to sum"). And then we'll put ("Enter a negative to exit!"). So, that's the prompt for the priming read. Now we need input = keyboard.nextInt();. Here we go. And we will say, while the input is greater than equal to zero, and there's the end of the while loop. So, as long as that's the case, we'll take that value that we just got and we're going to take the sum and do plus equals input. So, that's the same as sum = sum + input. And this is sentinel controlled. So, we're going to then re-prompt the user and as long as they're entering these non-negative values, then it will keep looping and keep adding to our sum. And then at the very end, we're going to print out the sum. So, System.out.println, we will say, sum is and then print out sum. So, let's do a couple of runs here. So, SumFun, we will run it.
And let's see what we've got here, enter a non-negative to exit. We'll say 100, 500 and 20, and then we'll say negative one. And it does in fact give us 620 right there. Let's run it one more time and see what we can get here.
Let's say for the priming read, we just put a negative five right off the bat. So, our sum zero, because it shouldn't be a negative five because we shouldn't be adding any kind of negative to the sum. The sum was initialized at zero. If we enter a negative here, that breaks out of the loop immediately and then we just print the sum. That was a lot of work but I hope you're having fun. Learning to code can be very enjoyable, however, it can also be extremely frustrating. But stay focused and keep practicing, and you'll do fine. In the next lecture, we will look at a couple of useful statements that can cause loops to behave differently than their typical behavior. I'll see you there.
John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.