• Interrupting the java loop. Loops in Java. Examples and description: for – Java loop

    When you need the same action to be performed several times or until a certain condition is met, loops come to our aid.

    IN Java language There are several ways to create loops. As you might have guessed, we will consider them all.

    The first way to declare a loop is to use the following construct: for (loop start condition; end condition; step at which the loop will go) (loop body)

    Let's move straight to the examples. Let’s say we have a task to display the phrase “hello world” 10 times. If you don't use loops, you can just write System.out.println("Hello world"); ten times and we will solve the problem. Let's use loops for this purpose. Create a new class and call it for example CuclesInJava. Now declare the loop condition (let it be 0), the end condition - 10, and the step. We will go in increments of one. In the body of the loop, place the line System.out.println("Hello world");

    Here is a code example:

    The result of this code will be 10 lines in a row of the phrase “Hello world!”

    How about writing something more complex. We have already learned the basic ones. Let's use them.

    Let's write a simple application that will display a warning line every time a step + some variable is equal to 5. I'm very bad at imagination))

    First, let's write a code that will accept as input a variable entered from the console. In the previous article, I gave an example of this code and we agreed that then I would explain how it works and where it came from. And now we will simply use it:

    Next, you need to write a loop that will start from zero and count to ten (as in the previous example). In the body of the loop we will write a conditional statement that will check whether this variable is equal to 5 and if so, then we will output the line “OK”. Here's what I got:

      import java.util.Scanner ;

      public class CuclesInJava(

      int variable = scanner.nextInt(); //we will get to this gradually and then it will be clear how it works

      for (int i = 1 ; i< 10 ; i++ ) {

      int newVariable = i + variable;

      if (newVariable==5) (

    It didn't turn out very complicated. With this example, I wanted to show how you can use loops with branches in conjunction.

    The next way to declare loops is with the construct: while(condition is true)(block of code to be executed). This design has another form:

    do(block of code to be executed)while(condition is true). The difference between the first and the second is that the second executes one loop regardless of whether the condition is true or not. You can think for yourself: first we execute the code, and then we check the condition. And even if the condition is not true, the code will still be executed once, at the time when in the first type of construction the condition is first checked and until it is true, the code will not be executed.

    The code should be intuitive. I think it's worth mentioning that with the while and do-while constructs you can "loop" program if the condition for exiting the loop is not specified or incorrectly specified. Look at the example above and think what would have happened if I had written not i—, but i++; or instead of i>0, i<0. Моя программа никогда не вышла бы из цикла и продолжала бы выводить строку Hello world! до тех пор, пока не завис компьютер. Поэтому, будьте очень осторожными с циклами и всегда следите, чтобы из них Ваша программа могла выйти или закончить работу.

    Well, an example with do-while:

    On this, I think, we can finish the article about loops in Java. As you can see, the designs are not very complex, but very useful. They will be especially useful when we get acquainted with arrays and strings.

    08/12/17 1.9K

    A Java While Do loop is a statement that allows you to run the same piece of code multiple times. This loop can be used to repeat actions when conditions are met.

    While Loop

    The while loop is the simplest to construct in the Java language. It consists of a while key, a loop condition, and a loop body:

    while (condition) ( // loop body )

    Each separate run of the loop body is considered an iteration. Before each iteration, the loop conditions are evaluated. Its body is executed only if the loop condition evaluates to true .

    The iterations of the loop change something, and at a certain point the condition evaluation returns false , at which point the loop ends. A loop whose condition never returns false is executed an infinite number of times. Such cycles are called endless.

    Example

    int num = 0; while (num< 10) { System.out.println(num); num++; }

    This example prints the numbers 0 through 9. Let's go through the code step by step. First we initialize the num variable with a value of 0. This will be the loop counter. When the program reaches while , the loop's conditions are evaluated. In our case 0< 10 возвращает значение true и исполняется тело цикла. Внутри цикла выводится переменная num , а затем увеличивается на 1 . На этом завершается первая итерация.

    After the first "run", the Java While loop condition is evaluated a second time. 1< 10 по-прежнему возвращает true , после чего запускается следующая итерация цикла. Один и тот же процесс повторяется несколько раз.

    The final iteration begins when the value of num equals 9 . The loop counter is displayed one last time and the value is incremented to 10. This time, a new iteration cannot be started because the loop condition evaluates to false . Since 10 is not less than 10.

    Thus, the loop runs as long as the loop condition is satisfied. Armed with this knowledge, you can create more complex and functional loops. Let's iterate through the array:

    String names = ("Doc", "Dopey", "Bashful", "Grumpy", "Sneezy", "Sleepy", "Happy"); int index = 0; while (index< names.length) { System.out.println(names); index++; }

    The concept of this example is similar to the previous one. We initialize the loop counter and iterate through the array until all elements are printed. As a result, iterating over arrays is a fairly common case, and Java has a better construct for this: the For loop.

    do-while loop

    The Java while do loop is similar to while , but has a significant difference: unlike while , the condition is checked at the end of each iteration. This means that the do-while loop is always executed at least once:

    do ( // loop body ) while (condition);

    Example

    do-while first executes the body of the loop and then evaluates its conditions. Depending on the result obtained, the loop stops or the next iteration starts. Let's look at a simple game "guess the name":

    Scanner scanner = new Scanner(System.in); String guess; do ( System.out.print("Guess the name: "); guess = scanner.nextLine(); ) while (!"Daffy Duck".equals(guess)); System.out.println("Congratulations! You guessed my name!");

    This while Java example uses Scanner to parse input from system.ini . This is the standard input channel that interacts with the keyboard in most cases. Simply put, we simply read the text that the player enters.

    In the game, you must ask the user at least once, and do this as long as the player enters the correct answers. The do-while loop is ideal for such cases. In the body of the loop, we get the user value and then check the correctness of the answer. The loop should run until the user input value equals Daffy Duck. If the correct answer is received, the loop stops and we congratulate the player on his victory.

    In conclusion

    Java's while true loops allow you to reuse pieces of code multiple times. Today we were introduced to Java while and do-while loops. They are similar in that they check conditions and execute the body of the loop if the condition evaluates to true . But at the same time, they have a significant difference: the condition of the while loop is checked before the iteration, and the condition of the do-while loop is checked at the end of each iteration. This means that the do-while loop is always executed at least once.

    This publication is a translation of the article “ Java's While and Do-While Loops in Five Minutes", prepared by the friendly project team

    A cycle is a fragment of a program that repeats itself many times.

    There are two types of loops in java: the "while" type and the "n-time" type.

    The first type of “while” is designed to repeat some action as long as some condition is met. Example: increase a number by 5 until it reaches three digits.

    The second type “n-time” is intended for repeating some actions a predetermined number of times. Example: multiply a number by itself 4 times.

    While loop (while and do...while statements)

    The while statement repeats the specified actions as long as its parameter is true.

    For example, such a loop will be executed 4 times, and “1 2 3 4” will be displayed on the screen:

    Int i = 1; while (i< 5) { System.out.print(i + " "); i++; }

    Such a loop will not be executed even once and nothing will be displayed on the screen:

    Int i = 1; while (i< 0) { System.out.print(i + " "); i++; }

    This loop will run endlessly, and the screen will display “1 2 3 4 5 6 7...”:

    Int i = 1; while (true) ( ​​System.out.print(i + " "); i++; )

    The condition that determines whether the loop will be repeated again is checked before each step of the loop, including the very first one. They say what's going on pre-check conditions.

    There is a cycle like “bye” with post-check conditions. To write it, a construction of do...while statements is used.

    This loop will be executed 4 times, and “2 3 4 5” will be displayed on the screen:

    < 5);

    This loop will be executed 1 time, and “2” will be displayed on the screen:

    Int i = 1; do ( i++; System.out.print(i + " "); ) while (i< 0);

    The body of the do...while loop is executed at least once. This operator is convenient to use when some action in the program needs to be performed at least once, but under certain conditions it will have to be repeated many times.

    Check out the following program (it guesses a random integer from a segment and asks the user to guess it by entering options from the keyboard, until the user guesses the number, the program will prompt him, telling him whether the guessed number is more or less than what the user entered):

    Import java.util.Scanner; public class Main ( public static void main(String args) ( // prog - a number created by the program // user - a number entered by the user int prog, user; // Generate a random integer from 1 to 10 prog = (int)(Math. random() * 10) + 1; System.out.println("I guessed a number from 1 to 10, guess it."); System.out.print("Enter your number: "); System.in); // Check if there is an integer in the input stream if(input.hasNextInt()) ( do ( // Read an integer from the input stream user = input.nextInt(); if(user == prog) ( System.out.println("You guessed it!"); ) else ( // Check if the number is included in the segment if (user > 0 && user<= 10) { System.out.print("Вы не угадали! "); // Если число загаданное программой меньше... if(prog < user) { System.out.println("Моё число меньше."); } else { System.out.println("Моё число больше."); } } else { System.out.println("Ваше число вообще не из нужного отрезка!"); } } } while(user != prog); } else { System.out.println("Ошибка. Вы не ввели целое число!"); } System.out.println("До свиданья!"); } }

    Make the following modifications to the program:

      The program should think of a number not from the segment , but an integer from the segment from [−10;10], excluding zero. At the same time, try to ensure that the distribution of random numbers generated by the program is uniform (i.e., if a zero lands, it cannot simply be replaced with some other number, for example, 1, because then 1 will be dropped with twice the probability than the rest numbers).

      The program should prompt the user that he made a mistake in the sign if the program guessed a positive number and the user entered a negative one. And vice versa.

    N-time loop (for statement)

    The for statement contains three parameters. The first is called initialization, the second is called repetition condition, and the third is called iteration.

    For (initialization; condition; iteration) ( //loop body, i.e. actions repeated cyclically)

    In the first parameter, you usually select some variable that will be used to count the number of repetitions of the loop. It's called a counter. The counter is given some initial value (they indicate from what value it will change).

    The second parameter indicates some limitation on the counter (indicate to what value it will change).

    The third parameter specifies an expression that changes the counter after each loop step. Usually this is an increment or decrement, but you can use any expression where the counter will be assigned some new value.

    Before the first step of the loop, the counter is assigned an initial value (initialization is performed). This only happens once.

    Before each step of the loop (but after initialization), the repetition condition is checked; if it is true, then the body of the loop is executed again. At the same time, the body of the loop may not be executed even once if the condition is false at the time of the first check.

    After completing each step of the loop and before starting the next one (and therefore before checking the repetition condition), an iteration is performed.

    The following program displays numbers from 1 to 100:

    For (int i = 1; i<= 100; i++) { System.out.print(i + " "); }

    The following program displays numbers from 10 to −10:

    For (int s = 10; s > -11; s--) ( System.out.print(s + " "); )

    The presented program displays odd numbers from 1 to 33:

    For (int i = 1; i<= 33; i = i + 2) { System.out.print(i + " "); }

    The presented program will calculate the sum of the elements of a fragment of the sequence 2, 4, 6, 8,... 98, 100. So:

    Int sum = 0; // We will accumulate the result here for (int j = 2; j

    The presented program will raise a number from a variable a to natural degree from variable n:

    Double a = 2; int n = 10; double res = 1; // We will accumulate the result here for (int i = 1; i<= n; i++) { res = res * a; } System.out.println(res);

    The presented program will display the first 10 elements of the sequence 2n+2, where n=1, 2, 3…:

    For (int i = 1; i< 11; i++) { System.out.print(2*i + 2 + " "); }

    The presented program will display the first 10 elements of the sequence 2a n−1 +3, where a 1 =3:

    Int a = 3; for (i=1; i<=10;i++) { System.out.print(a + " "); a = 2*a + 3; }

    In one cycle, you can set several counters at once. In this case, several expressions in iteration and initialization are separated by commas. Only one repetition condition can be specified, but it can be an expression containing several counters at once.

    The presented program will display the first 10 elements of the sequence 2a n−1 -2, where a 1 =3:

    For (int a=3, i=1; i<=10; a=2*a-2, i++) { System.out.print(a + " "); }

    The presented program will display the following sequence “0 -1 -4 -9 -16 -25”:

    For (int a=0, b=0; a-b<=10; a++, b--) { System.out.print(a*b + " "); }

    Terminating a loop early (break statement)

    Both the “while” type loop and the “n-time” type loop can be terminated early if you call the operator inside the loop body break. In this case, the loop will immediately exit; even the current step will not be completed (that is, if there were any other statements after break, they will not be executed).

    As a result of the following example, only the numbers “1 2 3 4 End” will be displayed on the screen:

    For (int a=1; a

    When the program executes the loop for the fifth time (enters a loop with a counter equal to 5), the condition under which the break statement will be executed will immediately be checked and found to be true. The remaining part of the loop body (output to the screen) will not be produced: the program will immediately proceed to perform the operations specified after the loop and beyond.

    Using the break statement, you can interrupt an obviously infinite loop. Example (the screen will display “100 50 25 12 6 3 1 0” and after that the cycle will stop):

    Int s = 100; while (true) ( ​​System.out.print(s + " "); s = s / 2; if(s == 0) ( break; ) )

    It makes sense to call the break operator only when some condition occurs, otherwise the loop will be completed ahead of schedule at its very first step.

    Int a; for (a=25; a>0; a--) ( break; System.out.print(a + " "); ) System.out.print("a=" + a);

    In the above example, output to the screen in a loop will not occur even once, and when the variable a is displayed on the screen after the loop, it turns out that its value has never changed, i.e. “a=25” will be displayed (and nothing more).

    Note also that the variable was declared before the loop began. When a variable is declared in the parameters of a loop, it turns out to be inaccessible outside of it, but in this case something else was required - to find out what value the counter will have after the loop ends.

    Tasks

      Create a program that displays all four-digit numbers in the sequence 1000 1003 1006 1009 1012 1015….

      Write a program that displays the first 55 elements of the sequence 1 3 5 7 9 11 13 15 17 ….

      Write a program that displays all non-negative elements of the sequence 90 85 80 75 70 65 60….

      Write a program that displays the first 20 elements of the sequence 2 4 8 16 32 64 128 ….

      Display all terms of the sequence 2a n-1 -1, where a 1 =2, that are less than 10000.

      Display all two-digit terms of the sequence 2a n-1 +200, where a 1 = -166.

      Create a program that calculates the factorial of a natural number n that the user enters from the keyboard.

      Display all positive divisors of a natural number entered by the user from the keyboard.

      Check whether the natural number entered by the user from the keyboard is prime. Try not to perform unnecessary actions (for example, after you have found at least one non-trivial divisor, it is already clear that the number is composite and there is no need to continue checking). Also note that the smallest divisor of a natural number n, if it exists at all, must be located in the segment.

      Write a program that displays the first 12 elements of the sequence 2a n-2 -2, where a 1 =3 and a 2 =2.

      Display the first 11 terms of the Fibonacci sequence. We remind you that the first and second terms of the sequence are equal to ones, and each next one is the sum of the two previous ones.

      For a natural number entered by the user from the keyboard, calculate the sum of all its digits (it is not known in advance how many digits will be in the number).

      In city N, tram travel is carried out using paper tear-off tickets. Every week, the tram depot orders a roll of tickets from the local printing house with numbers from 000001 to 999999. A ticket is considered “lucky” if the sum of the first three digits of the number is equal to the sum of the last three digits, as, for example, in tickets with numbers 003102 or 567576. The tram depot decided give a souvenir to the winner of each lucky ticket and is now wondering how many souvenirs will be needed. Using the program, count how many lucky tickets are in one roll?

      In city N there is a large warehouse in which there are 50,000 different shelves. For the convenience of workers, the warehouse management decided to order a plate with a number from 00001 to 50000 for each shelf from a local printing house, but when the plates were printed, it turned out that the printing press, due to a malfunction, did not print the number 2, so all the plates whose numbers contained one or more two (for example, 00002 or 20202) - you need to retype it. Write a program that will count how many of these erroneous plates were in the defective batch.

      The electronic clock displays time in the format from 00:00 to 23:59. Count how many times per day it happens that a symmetrical combination is shown to the left of the colon for the one to the right of the colon (for example, 02:20, 11:11 or 15:51).

      In the American army, the number 13 is considered unlucky, and in the Japanese - 4. Before international exercises, the headquarters of the Russian army decided to exclude numbers of military equipment containing the numbers 4 or 13 (for example, 40123, 13313, 12345 or 13040) so as not to confuse foreign colleagues. If the army has 100 thousand units of military equipment at its disposal and each combat vehicle has a number from 00001 to 99999, then how many numbers will have to be excluded?

    2010, Alexey Nikolaevich Kostin. Department of TIDM, Faculty of Mathematics, Moscow State Pedagogical University.

    Last update: 10/31/2018

    Another type of control structures are loops. Loops allow you to perform a specific action multiple times depending on certain conditions. Java has the following types of loops:

    for loop

    The for loop has the following formal definition:

    For ([initialize counter]; [condition]; [change counter]) ( // actions )

    Consider the standard for loop:

    For (int i = 1; i< 9; i++){ System.out.printf("Квадрат числа %d равен %d \n", i, i * i); }

    The first part of the loop declaration - int i = 1 creates and initializes counter i. The counter does not have to be of type int . It can be any other numeric type, for example float. Before the loop executes, the counter value will be 1. In this case, this is the same as declaring a variable.

    The second part is the condition under which the loop will be executed. In this case, the loop will run until i reaches 9.

    And the third part is incrementing the counter by one. Again, we don't necessarily need to increase by one. You can decrease: i-- .

    As a result, the loop block will run 8 times until the value of i becomes equal to 9. And each time this value will increase by 1.

    We don't have to specify all the conditions when declaring a loop. For example, we can write like this:

    Int i = 1; for (; ;)( System.out.printf("The square of %d is %d \n", i, i * i); )

    The definition of a loop remains the same, only now the blocks in the definition are empty: for (; ;) . Now there is no initialized counter variable, no condition, so the loop will run forever - an infinite loop.

    Or you can omit a number of blocks:

    Int i = 1; for(;i<9;){ System.out.printf("Квадрат числа %d равен %d \n", i, i * i); i++; }

    This example is equivalent to the first example: we also have a counter, but it is created outside the loop. We have a loop execution condition. And there is an increment of the counter already in the for block itself.

    A for loop can define and manipulate multiple variables at once:

    Int n = 10; for(int i=0, j = n - 1; i< j; i++, j--){ System.out.println(i * j); }

    do loop

    The do loop first executes the loop code and then tests the condition in the while statement. And as long as this condition is true, the cycle repeats. For example:

    Int j = 7; do( System.out.println(j); j--; ) while (j > 0);

    In this case, the loop code will run 7 times until j is equal to zero. It's important to note that the do loop guarantees that the action will be executed at least once, even if the condition in the while statement is not true. So, we can write:

    Int j = -1; do( System.out.println(j); j--; ) while (j > 0);

    Even though j is initially less than 0, the loop will still execute once.

    while loop

    The while loop immediately checks the truth of some condition, and if the condition is true, then the loop code is executed:

    Int j = 6; while (j > 0)( System.out.println(j); j--; )

    Continue and break statements

    The break statement allows you to exit a loop at any time, even if the loop has not completed its work:

    For example:

    < nums.length; i++){ if (nums[i] >10) break; System.out.println(nums[i]); )

    Since the loop is checking whether the array element is greater than 10, we will not see the last two elements on the console, since when nums[i] is greater than 10 (that is, equal to 12), the break statement will work and the loop will end.

    True, we will also not see the last element, which is less than 10. Now we will make sure that if the number is greater than 10, the loop will not end, but simply move on to the next element. To do this, we use the continue operator:

    Int nums = new int ( 1, 2, 3, 4, 12, 9 ); for (int i = 0; i< nums.length; i++){ if (nums[i] >10) continue; System.out.println(nums[i]); )

    In this case, when the loop reaches the number 12, which does not satisfy the test condition, the program will simply skip this number and move on to the next element of the array.

    In this tutorial, we'll learn how to re-execute parts of our code in a controlled manner by looking at different types of loops in Java. Let's take a closer look at cycles: while, do-while, for. We will try to determine in which cases which cycle is most suitable for use.

    Then we'll briefly look at the topic of random numbers ( randomnumbers). Let's look at Java-Class Random and how it can help us in our game.

    A loop, as the name suggests, is a way of executing the same piece of code as many times as necessary (without necessarily repeating the result of executing the code in the loop). The number of repetitions of the cycle can be either determined in advance or unknown to the programmer himself. We will look at the main types of loops that the language offers us to use. Java. And then we will introduce some of them into our game, thereby improving it.

    While Loop

    Cycle while has the simplest syntax. Remember if-instructions that we studied a little earlier. Into the conditional expression of the operator if(what is enclosed in brackets after the word if) you can put almost any combination of operators and variables. If the expression is true ( true), then the code enclosed in the body of the block if will be completed. Similarly in the loop while we put an expression that can be evaluated in true or false as shown in this code:

    Int x = 10; while(x > 0)( x--; //x is decreased by one each pass of the loop)

    What's going on here? First thing outside the loop while we declared a variable x type int and assigned this variable value"10". Then the cycle begins while, in the conditions of which it is written x > 0”– this means that the code written in the body of the loop while will be executed as long as the variable x more 0 and the condition will not reach the value false. Therefore, the code will be executed 10 times(x=10,x>0; x=9,x>0; x=8,x>0; x=7,x>0; x=6,x>0; x=5 ,x>0 ; x=4,x>0 ; x=3,x>0 ; On the first pass of the cycle x = 10, in the second already 9 , in the third 8 etc. And when x will be equal 0 , then the condition for entering the loop will not be satisfied, and the program will continue from the next line after the end of the loop.

    Same as in the operator if, a situation is possible in which the loop will not be executed even once. Take a look at the following example:

    Int x = 10; while(x > 10)( //some code //but it will never be executed while x is greater than 10)

    Additionally, there is no limit to the complexity of the condition expression or the amount of code that can be written in the body of the loop:

    Int playerLives = 3; int alienShips = 10; while(playerLives >0 && alienShips >0)( //All game code here //... //... // etc. ) //the program will continue here when either playerLives or alienShips = 0

    This loop will run until either the variable playerLives, or alienShips will not be equal to or less than zero. As soon as one of these conditions occurs, the expression in the condition will take the value false and the program will continue from the next line after the loop completes.

    It is worth noting that once the program enters the body of the loop, it will be executed even if the loop condition becomes false, somewhere in the body of the loop, because the condition is checked only upon entry:

    Int x = 1; while(x > 0)( x--; //x is now equal to 0 and the condition next time will be false //But this line will be executed //And this one //And even this one)

    In the example above, the body of the loop will be executed once. In addition, you can set a condition such that the loop will run forever - this is called endless loop. Here's an example:

    Int x = 0; while(true)( x++; //I will become very big!)

    The output of their cycle. Keyword break

    What if we really need to use endless loop, but so that we can decide at what moment to exit it. For this purpose in Java there is a keyword break. We can use break when we need to “exit” the loop:

    Int x = 0; while(true)( x++; //I will become very big! break; //No, you won’t! //the code here will not be reached)

    Surely you have already guessed that it is possible to combine various decision-making tools, such as if,else,switch inside our loop while and other cycles, which we will consider below. For example:

    Int x = 0; int tooBig = 10; while(true)( x++; //I will become very big! if(x == tooBig)( break; //No, you won’t. ) //the code here will be available until x is equal to 10)

    You can write down many more different variations, but for us it is more important practical application this knowledge, so we won’t go too deep now. Let's look at another concept that can be manipulated in a loop.

    Keyword continue

    continue works almost the same as break. Keyword continue will kick you out of the loop body, but then test the condition expression rather than continuing from the loop's closing curly brace, as would happen with break. The following example shows the use continue:

    Int x = 0; int tooBig = 10; int tooBigToPrint = 5; while(true)( x++; //I will become very big! if(x == tooBig)( break; ) //No, you won’t. //the code here will only be available until x is equal to 10 if(x > = tooBigToPrint)( //will no longer be printed on the screen, but the loop will continue continue; ) //the code here will be available until x is equal to 5 //code to print x to the screen)

    Explanation: we declare and initialize variables. We go into the loop and add to the value of the variable x unit (now x= 1). Checking "Is 1 equal to 10?" — false- first operator if is not executed. Next check“Is 1 greater than or equal to 5?” — false- second operator if is not executed. We output x to the screen.

    Let's consider the option when x will take the value 5 when entering the loop. We go into the loop and add to the value of the variable x unit (now x= 6). Checking "6 equals 10?" — false- first operator if is not executed. The next check is “6 is greater than or equal to 5?” — true- we go into the body ifcontinue, exit the loop and check the condition for entering the loop.

    Now the option is when x will take the value 9 when entering the loop. We go into the loop and add to the value of the variable x unit (now x= 10). Checking "Is 10 equal to 10?" — true- we go into the body ifbreak, exit the loop and the code will continue beyond the closing curly brace of the loop while.

    do-while loop

    Almost the same as the previous loop with the exception of one feature - the conditional expression execution check will occur after the loop body. This means that the cycle do-while will always be executed at least once. Take a look at the example:

    Int x = 0; do ( x++; ) while(x< 10); //x теперь = 10

    Keywords break,continue

    for loop

    Cycle for has a more complex syntax than while And do-while, since it requires a little more manipulation to initialize. Let's take a look at it first and then take it apart:

    For(int i = 0; i< 10; i++){ //Что-то, что должно произойти 10 раз будет записано здесь }

    How does the compiler see this? Like this:

    For(declaration and initialization; condition; change after each loop pass)( // body of the loop)

    • Declaration and initialization- we created a new one type variable int with name i and assigned it a value 0 ;
    • Condition– like other cycles discussed earlier, here we check the condition for entering the cycle. If the value is calculated as true, then we enter the body of the loop;
    • Change after each cycle- in the example above i++ means that after the next pass of the loop we get to the value of the variable i add one (1). Moreover, we can write in changing the variable and i to subtract one, for example:
    for(int i = 10; i > 0; i--)( //countdown ) //start key, i = 0

    Keywords break,continue can also be used in this cycle.

    Cycle for takes control of initialization, condition testing, and variable modification. Let's try this cycle in practice in our application immediately after we get acquainted with random numbers And methods.