2-A: Selection and Iteration

Conditions

A fundamental element of flow control is whether or not you want to execute a block of code. We use a conditional or if statement to test something. That test will result in a true or false value. If it's true, we'll execute the block of code. If it's false, we'll skip to the end of the block of code.

Loops

Loops are how we repeat commands or loop through items in a collection.

for loops

standard for loop

Most for loops look something like this:

The for statement has a declaration, condition and increment. But you can skip the declaration if you'd like. Let's say you want the counter to have a wider scope (so it can be accessed outside of the loop) like this:

foreach loop

Let's say I have an array or collection of numbers like this: int[] numberArray = [5, 10, 15, 20, 25];

Each number in that group has an address or index (that starts at 0). If I wanted to print the number 10 for example, I could write System.out.println(numberArray[1]);

So if I wanted to loop through (called iterating or traversing) all the items in this array, I could use a normal for loop like this:

But there's an easier form of the for loop that's meant to easily traverse through a collection. We'll go over some of the pros and cons of this method later.

while loops

Infinite loop

do-while loop

The do-while is rarely used but it's handy if you want to make sure the steps run the first time before the loop condition is tested. Read more.

This is a silly joke, not an actual way to resolve problems with your loops.

This comes up all the time in problems. It's a useful trick to avoid crashing your apps, too.

Last updated

Was this helpful?