Search⌘ K

Programs That Can Loop

Explore how to use Java while loops to execute code repeatedly based on a condition. Understand the importance of initializing and updating counters, and learn to avoid logical errors that cause infinite loops. This lesson helps you write efficient, clean code for repetitive tasks and prepares you to solve programming problems using loops.

We’ve found a way to break the strictly sequential flow of a program by pushing one or however many statements within an if block. This means that our lines of code, other than those in if-else blocks, will get executed line by line, in sequence. But some lines of code will only get executed if a condition is True, otherwise, another set of lines will become a part of the execution. Sequential or selective, each line of code only gets executed once, and then our computer fetches the next one, and then the next.

The while loop

Wouldn’t it be great for programmers if they could make the computer execute a block of code repeatedly while a condition is True?

Looping over the code
Looping over the code

For instance, if we’re required to print 1 three times, what would be our code?

Java
public class MyJavaApp {
public static void main(String[] args) {
System.out.println(1);
System.out.println(1);
System.out.println(1);
}
}

Let’s imagine we’re being asked by our boss to print 1 ten times. ...