JavaRush /Java Blog /Random EN /While Loop in Java

While Loop in Java

Published in the Random EN group

Introduction

Our very first programs were a sequence of instructions that were executed one after another. No forks. This is HelloWorld, which outputs a greeting phrase and arithmetic calculations to the console. After the first programs, we learned to branch, that is, the program performed certain actions depending on the conditions. Here's how you could code the air conditioner to turn on for heating and cooling:
if (tempRoom>tempComfort)
    airConditionerOn();
if (tempRoom<tempComfort
    heaterOn();
Let's take the next step. In everyday life, we often perform monotonous, repetitive actions, for example, peeling apples for a pie. This fascinating process can be described as:
  1. If there are apples in the basin, then follow steps 1.1 to 1.4:

    1. 1.1. Take an apple
    2. 1.2. Clean and cut it into slices
    3. 1.3. Place on the base of the pastry pie in a frying pan
    4. 1.4. Let's go back to step 1.
Operator while - 2
Let's say you have 10 apples, 2 hands and one knife. In life, you consistently clean the entire ten, guided by the same algorithm. How can you make the program do a repeating action with each apple?
  • Let us bind ourselves to the number of apples, but if we have few of them, some of the commands would be executed in vain without a “payload” (and, perhaps, we would cut ourselves while peeling a non-existent apple).
  • If there are more apples than our processing teams, some of the products would go unprocessed.
  • Such “code” is difficult to read, contains a lot of repetition, and is difficult to modify.

Loops are operators for performing actions multiple times.

The Java while loop (vile loop) works well in our case. This design organizes multiple actions into a concise and understandable structure. A while algorithm for slicing apples for a pie in Java might look like this:
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    положитьВПирог(яблоко.чистить().нарезать());
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
}
System.out.println('Apples for the pie are processed.');

Command Syntax

The first way to describe the while statement is as follows:
while(Логическое выражение) {
	// Loop body - periodically executed statement(s)
}
This is done as follows (step by step):
  1. We evaluate the Boolean condition that follows the while in parentheses.
  2. If the logical condition is true, then the statements in the loop body are executed, after executing the last statement in the loop body, go to step 1
  3. If the logical condition is false, then go to the first statement outside the while loop.

Loop with precondition

Since before executing the body of the loop, we always pre-calculate a logical expression (the condition for entering the loop), this type of while is often called a loop with a precondition. Let's build a table of the first ten integer, positive powers of a number:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(power <= 10) { // loop entry condition
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
    }
}
Console output result:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 10 = 59049
Process finished with exit code 0

Loop with postcondition

Second type of cycle:
do {
    // Loop body - periodically executed statement(s)
}while (Логическое выражение);
Performed as follows (steps):
  1. The body of the loop is executed (immediately after the do keyword).
  2. We evaluate the Boolean condition that follows the while in parentheses.
  3. If the logical condition is true, then go to step 1
  4. If the logical condition is false, then go to the first statement outside the while loop.
Two main differences from the previous type of loop: the body of the loop is executed at least once and the logical condition is checked after the body of the loop is executed. Therefore, this type of while loop is called a postcondition loop. This time we will display a table of powers of a number not exceeding 10000:
public static void main(String[] args) {
    int number = 3;// Number to be raised to a power
    int result = number;// Result of exponentiation
    int power = 1;// Initial exponent
    do {
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        result = result * number;
    }while (result < 10000); // loop exit condition
Console output result:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
Process finished with exit code 0
Pay attention to the changes in the code, comparing it with the version of the loop with a precondition.

Interesting facts about working with loops

Control commands in the body of the loop

There are two commands that affect the progress of the loop: break, the features of which we will show in the next chapter, and continue.
  • continue – stops execution of the body of the current loop and moves to the logical expression of the while operator. If the calculated expression is true, execution of the loop will continue.
  • break – immediately stops execution of the current loop and jumps to the first command outside it. Thus, the execution of the current loop is interrupted. We will look at it in more detail in the next topic.
Let's remember our fruit example. If we are not sure about the quality of the apples offered, we could change the code using the command continue:
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
    if (яблоко.плохое()) {  // method will return true for rotten, etc. apples
        яблоко.выкинутьВМусор();
        continue; // continue the loop, go to the condition number ofApplesIn the Basin>0
    }
    положитьВПирог(яблоко.чистить().нарезать());
}
The construction continueis often used when in the body of a loop it is necessary to execute commands when a certain condition occurs, for example, to perform actions when a sensor in the equipment is triggered (otherwise just continue the cycle of reading its indicators) or to calculate an expression only at certain steps of the cycle. An example for the last case is the calculation in a while loop of the sum of cubes of natural numbers whose square is less than their number:
public static void main(String[] args) {
    int sum = 0;    // total amount
    int i = 0;      // starting number of the row
    int count = 20; // amount of numbers
    while(i<=count) {
        i++;        // take the next number, i++ is equivalent to i=i+1
        if (i*i<=count)  // if the square of the number is less
            continue;   // number of numbers - do not count the sum
                        // move on to the next number in the loop
        sum += i*i*i; // otherwise, we calculate the sum of cubes of numbers
    } // sum += i*i*i - notation similar to sum = sum + i*i*i
    System.out.println(sum);// print result
}

Endless cycle

Данные управляющие команды чаще всего находят применение в бесконечном цикле. Его так называют, потому что логическое condition выхода никогда не выполняется. В codeе он выглядит примерно How:
while(true) {
    // Loop body
}
В этом случае и пригодится применение команды break для организации выхода из него. Этот вид цикла имеет место при ожидании внешних условий, которые формируются за пределами логики тела цикла. Например, в играх, эмулирующих виртуальный мир вокруг героя (выход из цикла = выход из игры), операционных системах. Или при использовании алгоритмов, возможно, улучшающих результат с каждым последующим вызовом в цикле, но ограничивая их по времени or наступлению внешнего события (шашки, шахматы or предсказание погоды). Следует помнить, что в обычных условиях бесконечные циклы – одна из проблем неустойчивости программы. Для демонстрации вернёмся к степеням числа:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(true) {
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        if (power>10)
            break; // exit from the loop
    }
}
Результат вывода на консоль:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 10 = 59049
Process finished with exit code 0

Вложенные циклы

Вот мы и подошли к завершающей теме о наших циклах. Вспомним о яблочном пироге (надеюсь, вы не голодны в данный момент) и наш «цикл»:
  1. Если в тазике есть яблоки, выполняем шаги с 1.1 по 1.4:

    1. 1.1. Берем яблоко
    2. 1.2. Чистим и нарезаем его дольками
    3. 1.3. Помещаем на основание пирога из теста на сковороде
    4. 1.4. Возвращаемся на шаг 1.
Подробнее распишем процесс нарезания дольками:
  1. Число долек = 0
  2. Пока число долек < 12, выполнить шаги с 2.1 по 2.3

    1. 2.1. Отрезать очередную дольку от яблока
    2. 2.2. Кол-во долек ++
    3. 2.3. Возвращаемся на шаг 2
И вставим в наш кондитерский алгоритм:
  1. Если в тазике есть яблоки, то выполняем шаги с 1.1 по 1.6:

    1. 1.1. Берем яблоко
    2. 1.2. Очищаем его от кожуры
    3. 1.3. Число долек = 0
    4. 1.4. Пока число долек < 12, выполнить шаги с 1.4.1 по 1.4.3
      1. 1.4.1. Отрезать очередную дольку от яблока
      2. 1.4.2. Кол-во долек ++
      3. 1.4.3. Возвращаемся на шаг 1.4
    5. 1.5. Помещаем дольки на тестовое основание пирога из теста на сковороде
    6. 1.6. Возвращаемся на шаг 1.
Получor цикл в цикле. Подобные конструкции весьма частые. Для завершающего примера построим таблицу умножения, которые школьники 90-х видели на обложках тетрадей в младших классах.
Operator while - 3
public static void main(String[] args) {
    // Display the values ​​of the second multiplier in the line
    System.out.println("    2  3  4  5  6  7  8  9");
    int i = 2;      // first multiplier, assign starting value
    while(i<10) {   // First loop, execute while the first multiplier is less than 10
        System.out.print(i + " | ");// Display the first multiplier at the beginning of the string
        int j = 2;                  // second multiplier, starting value
        while (j<10) { // Second loop, execute while the second multiplier is less than 10
            int mul=i*j; // Calculate the product of factors
            if (mul<10)  // If it contains one digit, print two spaces after it
                System.out.print(mul + "  ");
            else   // otherwise output the product and after it - one space
                System.out.print(mul + " ");
            j++;     // Increase the second multiplier by one,
        }            // Go to the beginning of the second loop (while (j<10 ).... )
        System.out.println(); // Move to the next line of output
        i++;                  // Increase the first multiplier by one,
    }                         // Go to the beginning of the first loop (while ( i<10 ) ....
}
Результат вывода на консоль:
2  3  4  5  6  7  8  9
2 | 4 6 8 10 12 14 16 18
3 | 6 9 12 15 18 21 24 27
4 | 8 12 16 20 24 28 32 36
5 | 10 15 20 25 30 35 40 45
6 | 12 18 24 30 36 42 48 54
7 | 14 21 28 35 42 49 56 63
8 | 16 24 32 40 48 56 64 72
9 | 18 27 36 45 54 63 72 81
Process finished with exit code 0
Циклы (в частности, оператор while) – один из фундаментальных кирпичиков построения программ. Решая задачи на JavaRush, вы изучите все их разнообразие, разберёте тонкости функционирования и получите практические навыки их применения.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION