Java for Humans {Control Flow Statements: Loops}

Lincoln W Daniel
Jan 20, 2016 · 8 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

We’ve come a long way from the last time we learned about control flow statements in the Decisions chapter. Great work on making it this far. This chapter will cover loops, which allow you to execute blocks of code more than once.

In the Decisions chapter, we learned that Java executes our program line by line from top to bottom. To change that, we could use if statements to only execute a block of code when a condition is true and another block of code otherwise. That is the basis of control flow in Java. With decision-making statements, we can choose to skip some lines of code during execution, but what if we want to repeat a line of code multiple times while a condition is true? That’s where loops come into play.

Why Loops are Important & Useful

Loops in Java allow us to repeat some of our code a fixed number of times or so long as a condition remains true. There are three basic forms of loops in Java, but we will only be focusing on two of them here because they are the most important and useful ones for beginners. We will learn about the for statement and the while statement. Both statements allow us to loop over blocks of code so long as a condition is true, but they do so a little differently from one another.

For Loop

The for statement allows us to loop over a block of code until a certain condition is satisfied. Because it loops, programmers often refer to it as the for loop. The for loop is best when you want to do something for a fixed number of times.

Say we want to loop over a range of numbers and print out each one along the way. We can do this best with a for loop. We will start from the first number, print it out, move to the next number to do the same thing, and continue until we’ve printed each number. Let’s print the numbers zero through nine:

for(int count = 0; count < 10; count++) {
System.out.print(count + " | ");
}
//prints "0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | "

Let’s take a look at the first line of the for loop and the three parts necessary to make it work. There is an initialization expression, termination expression, and a increment expression in that order.

The Starter: Initialization

The initialization expression initializes the loop and is only executed once, when the loop starts. This is where you must declare and initialize a variable, usually of type int, to hold an initial number that will be used to loop until it reaches a certain value. This can be thought of as the start of the range to iterate over. In our case, we started at zero (0).

The scope of the variable declared in the initialization expression extends from its declaration to the end of the for loop — until the closing curly brace } of the for loop’s block of code. This variable will be used by the termination and increment expressions during the lifetime of the loop. It can also be used in the body of the for loop as we did to print out the current number in our range. If the variable is not needed outside of the scope of the loop, it’s best to declare it in the initialization expression. Otherwise, we could declare the variable before the for loop and initialize it in the initialization expression, like so:

int count;
for
(count = 4; count < 10; count++) {
System.out.print(count + " | ");
}
//prints "4 | 5 | 6 | 7 | 8 | 9 | "
System.out.print("The next number would be " + count + ".");
//prints "The next number would be 10."

There, we printed the numbers four through nine in the loop, and we finished by printing what would have been the next number to print had we not stopped the loop at nine. Had we not declared the count variable before the for loop, we would not have been able to use it outside the scope of the for loop as we did there.

Although we named our initialization variable “count”, you will usually see it named “i”, “j”, or “k” as a convention.

The Terminator: Termination Expression

The for loop will continue looping until the termination expression evaluates to false. The termination expression is evaluated before each iteration of the loop and it must return a boolean to decide whether or not to continue looping. If the boolean returned is equal to true, we will run the body of our for loop again. In our case, because we want to print numbers from four through nine, we want the loop to terminate after it prints nine. It does exactly that.

The Incrementer: Increment Expression

This is one of those times I’m going to make up a word: the increment expression is the incrementer of the for loop. The increment expression is executed after each iteration of the loop to increment the variable we initialized in the initialization expression by use of the ++ operator. That allows the termination expression to know how many times the loop has looped. In our case, the initialization variable, count, starts at 0 and it’s printed out, then the incrementer increments it and the next iteration of the loop runs to print the new value count— 1 — and continues that way until 9 is printed. Finally, the incrementer increments the value of count to 10, but the terminator says, “No, no, no, 10 is not less than 10, so we are done here.”

Our example may seem trivial, but the for loop is a useful tool for easily and dynamically executing blocks of code multiple times without writing the same code more than once. In the Arrays chapter, you will see how we can use a for loop to iterate through the indices of an array to access each element one by one and manipulate them.

While Loop

The while statement is often referred to as the while loop because it continually loops over and executes a block of code statements while a given condition, or a set of conditions, is true. It is simpler to set up than the for loop because it only needs one expression, a termination expression, to evaluate before each iteration:

while (conditionIsTrue) {
//do something
}

A simple application of the while loop would be to print all numbers from zero through nine. It will look much similar to what we did with the for loop:

int number = 0;
while(number < 10) {
System.out.println("Current number = " + number);
//increment the number to move to the next
number++;
}
/*Prints:
Current number = 0
Current number = 1
Current number = 2
Current number = 3
Current number = 4
Current number = 5
Current number = 6
Current number = 7
Current number = 8
Current number = 9
*/

Again, that may seem trivial, but imagine the things you could do with loops. A loop may be used to keep your television on until you push the “off” button. Think about your microwave; much like a timer, it likely uses a loop to continue heating up your food until the time you set runs out. If you play video games, you may notice that the game continues to run until you turn off your game console or your computer. That’s a while loop at work:

while(offButtonNotPushed && userStillEngaged) {
//keep the game on for the user to continue playing
}

That’s a quick example of a while loop that evaluates multiple conditions before each iteration over its body. That while loop will continue looping so long as the user did not push the off button and the user is engaged in the game.

The && operator performs the logical And operation by combining two boolean expressions and returning true if and only if both expressions evaluate to true.

Break Statement

Loops are great, but sometimes we want to end them before they end themselves. If we have a loop iterating over a block of code, it will continue to do so until a particular condition becomes false. Another way to end a loop is to break out of it when another condition becomes true during an iteration and we no longer want to continue looping.

Say you want to continue eating cookies until your stomach is full, but there’s only so many cookies available. If we run out of cookies to eat, we shouldn’t keep trying to eat cookies even if we are still hungry. Instead, we should break out of the loop. We can simulate this situation with a while loop like so:

int numCookiesEaten = 0;
int cookiesNeededToBeFull = 10;
int numCookiesLeftInCookieJar = 8;

Random randomCookiesGenerator = new Random();
int numCookiesToEatThisTime;

int numCompletedIterations = 0;
while(numCookiesEaten < cookiesNeededToBeFull) {
numCookiesToEatThisTime = randomCookiesGenerator.nextInt(numCookiesLeftInCookieJar) + 1;

//make sure we aren't trying to eat more cookies than exists in the cookie jar
if(numCookiesToEatThisTime > numCookiesLeftInCookieJar) {
numCookiesToEatThisTime = numCookiesLeftInCookieJar;
}

System.out.println("< Eating " + numCookiesToEatThisTime + " cookies this time.");

numCookiesEaten += numCookiesToEatThisTime;
numCookiesLeftInCookieJar -= numCookiesToEatThisTime;

if(numCookiesLeftInCookieJar < 1) {
System.out.println("\n#No cookies left to eat :(");
break;
} else {
System.out.println("> " + numCookiesLeftInCookieJar + " cookies left in jar");
}

//increment number of times we've looped
numCompletedIterations++;
}
/*Prints:
< Eating 4 cookies this time.
> 4 cookies left in jar
< Eating 2 cookies this time.
> 2 cookies left in jar
< Eating 2 cookies this time.

#No cookies left to eat :(
*/

System.out.println("Completed " + numCompletedIterations + " iterations.");
//Completed 2 iterations.

There, you can see we need to eat ten cookies before we are full, but there are only eight cookies in the cookie jar to eat. During each iteration of the loop, we eat a random number of cookies from the cookie jar. At the end of each iteration, we increment the value of the numCompletedIterations int variable by one. At some point, we will definitely run out of cookies to eat before our stomach is full. At that point, we use the break keyword to break out of the loop.

Notice that after invoking break, we print how many full iterations we made through the while loop. It says we only completed two iterations because on the third iteration, we broke out of the loop before increasing the value of numCompletedIterations a third time.

Play around with the supporting code and find other ways to use the break statement with both the while and for loops.


ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade