• 15 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 28/03/2024

Use the right loop to repeat tasks

Imagine you have a block of code you need to repeat multiple times. You can wrap it in a function and call that function as many times as you need to. That could do the trick, however, most of the time you don't even know in advance how many times you need to call it.

Loops solve this issue!

A loop, in programming, is a technique that allows you to repeat one or more instructions without having to retype the same set of instructions multiple times.

Use enumerated loops for known number of iterations

Enumerated loops are loops that are used when you know in advance how many times you want to loop. In Java, these are called for loops.

With these, you can provide the number of iterations to be performed:

  1. As an integer value

  2. As the result of an expression that generates an integer value

For loops with an integer value

Here is an example of a for loop that repeats a statement five times:

for (int i=0; i<5;i++) {
    System.out.println("Clap your hands!");
}

In this set of instructions, we have an enumerating variable i that is responsible for the count of executions. The equivalent code if we were not using a loop would be:

System.out.println("Clap your hands!");
System.out.println("Clap your hands!");
System.out.println("Clap your hands!");
System.out.println("Clap your hands!");
System.out.println("Clap your hands!");

Can you imagine if we wanted to clap not five, but 42, or 1001 times?

The general syntax for the for statement is as follows:

for (initialization; termination; increment) {
    // list of statements 
}
  1. The initialization is an expression that initializes the loop. It generally declares and assigns an iterator. In our example, we declare an iterator named i of type int with a value of 5.

  2. The termination is an expression that is evaluated before each loop execution. When it evaluates to false, the loop stops. In our example, the termination expression is i<5, which means the loops stops when i reaches the value of five.

  3. An Increment is an expression that is evaluated each time an iteration is performed. In our example, the increment is i++. This means we add 1 to the value of i each time we go through our loop.

  4. The list of statements is located between{ and  }. It is the code that is run each time the loop is executed.

For loops with collections

Use enumerated loops when you need to iterate over an array or a collection. Here is an example for arrays:

int[] myArray = new int[]{7,2,4};
for (int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

As we saw in part 1, an array has a length property that returns the number of elements in the array. In this example, it is used as the termination of the for loop. Sometimes you don't care about the index and just want to display the value contained in the array or the collection. In that case, Java provides an enhanced for construct that has the following general syntax:

for (int number: myArray){
    System.out.println(number);
}

With the enhanced for, you simply need to define a variable of the type of the array or collection you are looping over. This variable will be assigned the value of each element of the array or collection until you have reached the end.

The for loop is great when you want to loop a predefined number of times or over all the elements of an array. When it is not the case, Java provides a more general way of looping with conditional loops.

Loop until you reach a condition with while loops

Conditional loops are also called while loops. They come in two types:

  • while

  • do/while

You can guess by the name, the loop needs to keep going while … something… or "as long as." It is a little like a combination of a for loop and an if statement. The number of repetitions is not defined by the lower and upper limits of an enumerator, but by a condition like that of an if statement.

While loop

Here's what the syntax looks like:

while (logicalExpression) {
// list of statements
}

It can be interpreted as "as long as the logical expression is true, repeat the instructions."

This is how it works in detail:

  1. The program verifies that  logicalExpression is true

  2. If it is false: the instructions are ignored. You do not even enter the body of the loop located between {  and  }.

  3. If it is true: the list of statements inside { and } are executed.

  4. Once the instructions are executed, you return to step one.

Let's look at an example to try:

int numberOfTrees = 0;

while (numberOfTrees < 10) {
    numberOfTrees += 1;
    System.out.println("I planted " + numberOfTrees + " trees");
}

System.out.println("I have a forest!");

This will produce the following result:

I planted 1 trees
I planted 2 trees
I planted 3 trees
I planted 4 trees
I planted 5 trees
I planted 6 trees
I planted 7 trees 
I planted 8 trees
I planted 9 trees
I planted 10 trees
I have a forest!

At each loop turn, numberOfTrees is incremented by one. When the variable reaches the value  10, the numberOfTrees <10 is no longer true. Terminate the loop and go on with the rest of the code in the program. In this case, it prints"I have a forest!".

❗️The following is important to keep in mind: using while loops can cause a program to crash. ☠️ When the expression remains true forever, the program gets stuck in the loop, causing something called an infinite loop:

boolean theSunIsUp = true;
while (theSunIsUp) {
    print ("Stay awake...forever!"); 
    // theSunIsUp never changes
}
// we never reach this
print ("Go to sleep!");

It's a common and easy mistake to make. So, pay attention! 

As you can see, the while condition is checked BEFORE the corresponding block of code can be executed even one time!

Do-while loop

Do-while loop is very similar to the first one, however, the condition is placed at the end of the corresponding block of code. This way, the block of code will always be executed at least once.

Here's how the syntax looks:

do {
// instructions
} while(logicalExpression);

Let's look at an example:

int pushUpGoal = 10;
do{
    print ("Push up!");
    pushUpGoal -= 1;
} while(pushUpGoal > 0);

This way, at least one push-up is performed before the condition is even checked. Let's tweak it a bit to demonstrate the difference from the original while loop:

Let's look at an example:

// While loop
int pushUpGoal = 0;
while(pushUpGoal > 0) {
    System.out.println ("Push up!");
    pushUpGoal -= 1;
    }

// do/while loop
int pushUpGoal = 0;
do{
    System.out.println ("Push up!");
    pushUpGoal -= 1;
} while (pushUpGoal > 0);

You can see that using the original while loop will perform no push-ups. The the do/while loop will cause a push-up to be performed once.

Skipping some instructions inside a loop

Within each type of loop, there might be situations when you want to skip some iterations or interrupt the whole loop prematurely upon a certain condition.

For example, you may want to repeat something 10 times, but skip (or partially skip) when the value equals 2 or 5. In Java, to skip an iteration in the loop use a continue statement:

for ( int i=0; i <10; i++) {
    // statements executed for each iteration
    if (i == 2 || i == 5) {
        continue;
    }
    // statements not executed when i == 2 or 5
} 

You may also interrupt the sequence completely, for example, if you want to find an element in an array and stop looking once found:

In Java, to interrupt an execution sequence, use a break statement:

String[] basket = new String[]{"apple", "orange", "banana"};

for (int i =0; i<basket.length;i++) {
    if (basket[i] == "orange") {
        System.out.println ("I have an " +basket[i]+ " !");
        break;
    }
} 

Once you find an item you are looking for, stop browsing the rest of an array.

Summary

In this chapter, you've learned two types of loops:

  • Enumerated loops execute a set of instructions a fixed number of times based on the lower and upper limit values of the enumerator.

  • Conditional loops execute a set of instructions until a defined condition is satisfied.

  • A common mistake to watch out for with conditional loops: infinite loops!

  • Iterations in a loop can skip some instructions within the loop using command continue.

  • The loop cycle can be interrupted and the loop can be prematurely exited using using the command break.

Exemple de certificat de réussite
Exemple de certificat de réussite