While Loop


while (condition) {
    // code that will be repeated
    // while the condition is true

Computers can tirelessly repeat the actions tens, hundreds, thousands of times. Programming for repetitions uses cycles.

Let’s write a function with a cycle that will display numbers from 1 to the argument number:

public static void main(String[] args) {

static void printNumbers(int lastNumber) {
    var i = 1;

    while (i <= lastNumber) {
        i = i + 1;

The while construct reads: “do what is indicated in the body of the loop while the condition (predicate) i <= lastNumber is true”. At the same time, the truth of the condition is checked before each execution of the loop body, including before the first one.

The while loop consists of three elements:

  • Keyword while.
  • Predicate in brackets after while.
  • Code block in curly brackets (loop body)

Each body execution is called an iteration. In our example, the call printNumbers(3) spawned three iterations, on each of which the variable i was displayed.

The most important thing in the cycle is completion (exit). The process that generates the cycle must eventually stop, otherwise the cycle will continue indefinitely. The responsibility for stopping lies entirely with the programmer.

Often, ensuring the finiteness of a cycle comes down to introducing a variable called “counter”, firstly because it’s so easy to convey the idea of “repeat N times”, and secondly, the value of the counter can be used in the body of the cycle itself - as in our example i for print. First, the counter is initialized, that is, it is given an initial value. In our example, this is done by the instruction i = 1. Then in the cycle condition it is checked whether the counter has reached its limit value.

In our example, the limit value is determined by the function argument. If the cycle condition is not met, the body is not met and the interpreter moves on, following the instructions after the loop. But if the condition of the cycle is true, then the body in which the key element of the stop is located is the change in the counter. It is usually done at the end of the body. In our example, the line i = i + 1 is responsible for the change.


Modify the printNumbers function so that it prints the numbers in reverse order. To do this, go from the top to the bottom. That is, the counter should be initialized with the maximum value, and in the body of the loop it should be reduced to the lower limit.

Sample call and output:

// => 4
// => 3
// => 2
// => 1
// => finished!

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community
Exercise available only for signed users.

Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on GitHub.