First Steps in Java — Part 7

mike dietz
5 min readMay 6, 2020

--

Loops

1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input | 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays

0: Intro | 1: Setup | 2: Data Types, Sizes and Variables | 3: Get Some Input| 4: Operators | 5: Strings | 6: Conditionals | 7: Loops

…over and over and over again.

Yesterday, we introduced conditionals with the structures of the if…else if…else statement and the switch, which execute a block of code one time.
Today, we look at some structures that are designed to execute a block of code numerous times. Code along you go through this unit, create a file and name it Loops.java.

Loops

A loop runs a block of code repeatedly while a condition is true. A loop is an iteration statement. An iteration is a repetition of a process.
There are different types of loops.

While Loop

It checks the conditional statement first before it runs. Only if the condition is true, it executes the block of code and continues to execute until the condition evaluates false.
while(condition) {
// ...do this
}

We create a simple example. We have a number that has an initial value of zero and it increments. While this number is smaller than 2, we print it to the screen. What result do you expect?
int number = 0;
while(number < 2) {
number++;
System.out.println(“This is number “ + number);
}

We declare an integer variable and initialize it to zero.
int number = 0;

We set the condition: while the number is smaller than 3.
while(number < 2)

We declare the block of code that should be executed while the condition is true. The number should be incremented and the number should be printed.
{
number++;
System.out.println(“This is number “ + number);
}

Did you get the expected result? Let’s analyze the code:
We start with a value of 0. The condition is true, therefore, the code gets executed, i.e. the number is incremented to 1 and then printed. We see “This is number 1” on the screen.
The number is 1, the condition is true, the code gets executed again and the number is incremented to 2.
Now the number is 2, the condition evaluates to false, no code is executed and the loop is finished.

Do-While Loop

The only difference to the while loop: it checks the conditional statement after the run, i.e. it runs at least once, even if the starting condition is not met.

do {
// code
} while (condition);

See the following example. The initial number is 5, the condition applies to numbers that are smaller than 2, i.e, the condition is not met. And yet, the first number is printed.

int doWhileNumber = 5;
do {
doWhileNumber++;
System.out.println(“This is number “ + doWhileNumber);
}

while(doWhileNumber < 2);

For Loop

A for loop has an iteration statement that contains the initialization of the variable, the condition when the code is to be executed and the counter, which is one of the unary operators that increment or decrement a whole number.

for (expression for initalization; expression for condition; expression for updating) {
// code to execute
}

Declare an integer variable i and initialize it with a value of 3: int i = 3;
Set the condition that i has to be larger than 0: i > 0;
Set the counter, the unary operator —-that decrements the number: i--
While this condition is true we print the number to the screen.
Once the for loop finishes, the next line of code is executed.

for (int i = 3; i > 0; i--) {
System.out.println(“on the count of “ + i);

}
System.out.println(“GO“);

Conditional in For Loop
You can use conditionals in loops. Let’s create a loop that prints the digit 0 for the odd indices and 1 for the even ones.
We create a for loop and implement an if statement that checks if the index is odd or even.
for (int index = 0; index < 8; index++) {
if (index % 2 == 0) {
System.out.print(“0”);
} else {
System.out.print(“1”);
}
}

Nested For Loop
You can also nest loops. In the following example, we will use an if-else statement in a nested loop and apply what we learned in the last example.
We create an 8 x 8 checkerboard with X for the black and O for the white fields.
We have an outer loop for the rows and an inner loop for the columns.
For the even rows, we want the condition that X will be printed for an odd number and O for an even.
O X O X O X O X

For the odd rows, we want a reverse order, i.e. O for the odd fields and X for the even ones.
X O X O X O X O

We already learned how to print Xs and Os in one line. The challenge is how to alternate the order in odd and even rows. Here’s the solution:
The index of our first row is 1. The index of our first column is 1. We add the indices and have an even result, i.e. 2. Therefore, the field of the first column in the first row is an X.
The index of our second row is 2. The index of our first column is 1. Now, we get 3 for adding the indices, which prints an O. We need to create an if statement that allows us to add the indices of rows and columns.

int rows = 8;
int columns = 8;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if ( (i + j) % 2 == 0) {
System.out.print(“O “);
}
else {
System.out.print(“X “);
}
}
System.out.println();
}

The matrix is filled row by row. The inner loop runs completely through for each new row, i.e. the outer row is at index 1 and the complete inner loop runs through all the column indices, prints the Xs and Os, and completes. Then, the outer loop executes a System.out.println(); . The first iteration is completed and the outer loop advances to row index 2.
This process is repeated until all 8 rows are executed.

Infinite Loop

Unintentional infinite loops cause a stack overflow and the application will crash. This happens when the loop cannot exit. This example is an unintentional infinite loop and will crash your application. No need to reproduce it.
int num = 0;
do {
num++;
System.out.println(num);
}
while (num > 0);

No condition will evaluate to false. Therefore, the loop will continue until the memory stack is full.

Get the code for this lesson at GitHub.

We reached the end of this lesson. Tomorrow we will talk about methods in Java.

--

--