Infinite for (Java) loop. For and while loops in Java

Java, like almost any programming language, has tools for ensuring that a certain piece of code is repeated many times, or loops, as they are commonly called. Loops in Java are represented by statements such as for and while, as well as their variations. Typically, loops are used to traverse one-dimensional and multidimensional arrays and iterable data structures (including collections) in order to find certain elements and further operations with them. However, this is not the only way to use such a tool as java loop. Examples of use will be provided as they are reviewed.

Java: description and examples

The fundamental loop operator in Java is while. The code fragment enclosed in its body will be repeated until the condition of the expression enclosed in parentheses after it satisfies the logical value of truth. General form The while statement looks like this:

while(condition) (

//loop body

As soon as the value of the logical condition ceases to be true, the code enclosed in the body of the loop will stop executing and control will be transferred to the line immediately following it.

If the body of the loop contains only one statement, then braces You don’t have to put them, but it is considered good form if they are always there. The figure above shows a block diagram of the operation of this operator.

For clarity, let's look at the example presented in the figure below:

The declared variable count initially has the value 1. Next we see logical expression, enclosed in parentheses after the operator name. It will be true, i.e. return true as long as the value of the count variable is less than or equal to 10. In the body of the loop, with each pass (iteration), the value of the variable is increased by 1 and displayed on the console screen. Notice that when the variable reached 11, the loop stopped running.

If the value of the count variable was initially equal to 11, then the loop condition would be false, and the program would not even enter its body.

It is worth noting that Java syntax allows you to use the while statement without a body. Let's give an example. Let's say we have two variables i = 100 and j = 200, we are faced with the task of programmatically calculating their arithmetic mean - for this we can use the “hollow” while:

while(++i< --j);

As a result, the value of any of the two variables will be equal to the average of their original values. As you can see, the loop worked perfectly without a body and completed everything necessary actions in conditional terms.

do-while loop

In the previous examples, if the conditional expression initially returned false, then program execution would ignore the body of the loop and move on. However, situations often arise in which execution of the code contained in the body of the loop is required at least once, regardless of the truth of conditional expression. In other words, it happens that checking the truth of a conditional expression is required not at the beginning, but at the end of the loop. This functionality can be provided by a variety while loop called do-while. It has the following form:

do(
//loop body

) while(condition);

As we can see, first the body of the loop is executed, and only then the truth of the condition is checked - and so on every iteration.

The code above will work in much the same way as with a regular while. However, if we set count to 11, the body of the loop would still be executed once before the statement could test the truth of the expression.

Description and examples of for - Java loop

Represents a universal and efficient language form in Java. Up to the fifth Java versions The SDK had only one traditional form of the for operator, and then a new one appeared - for each. IN this section We'll look at the traditional form of the operator. for Java the loop looks like this:

Before control is transferred to the code in the loop body, the variable i, which acts as a counter, is first initialized. Next, a conditional expression is checked that compares the counter to a specific value, and if it returns true, the body of the loop is executed. Then the counter value is changed by a predetermined step and the conditional expression is checked again, and so on until the condition becomes false. The flowchart below illustrates all stages of the cycle.

For a better understanding, here is an example of how a Java for loop works:

We see that the loopVal variable is used as a counter. After each iteration of the loop, its value will increment by 1, and this will continue until it reaches 11. Note that a control variable can be declared outside of a for statement, but if you do not intend to use this variable anywhere other than in a loop, it is recommended to declare it directly in the statement. Keep in mind that a variable declared in the statement itself has a scope within that same loop.

There are situations when you need to declare several loop control variables. For Java, a loop allows you to specify two or more variables separated by commas, and do this both during their initialization and during iteration. Such an operator will look like this:

for(int i = 1, int j = 10; i< j; ++i, --j) {}

With each iteration, the value of variable i will increase by 1, and the value of variable j will decrease by 1. Iterations will be performed until i becomes greater than or equal to j.

Features of using the for operator

The for loop is a fairly flexible design because all three of its parts (initialization, condition, and increment/decrement) can be used for other purposes. For example, instead of a conditional expression with a control variable, you can substitute any logical variable.

boolean exit = false;

for (int i = 0; !exit; ++i) (

In the example above, we can observe how the operation of the loop is absolutely independent of the control variable i and the number of iterations depends solely on the moment at which the exit variable becomes true. Moreover, the control variable can be completely removed from the loop and this will not affect its operation in any way: for(; !exit;) (). While this is not the smartest way to program, it can sometimes be useful. The main thing is to provide for a situation in which the variable will take the value necessary to exit the loop, so as not to turn it into an infinite one.

For Java, a loop can also be declared in this way: for(; ;) (). This is a typical example of an infinite loop with special interrupt conditions. We will talk about how to interrupt this kind of cycles a little later.

For each style loop

The Java foreach loop is always used to sequentially iterate through the elements of an array or any other and perform certain repeating operations on them. An example of this form of the for statement is shown below:

Name is declared as an iterative variable, and the previously declared array of strings names acts as the second argument of the operator. The name variable will take the values ​​of each array element in turn until all its elements have been retrieved. It should be noted that the type of the variable must be compatible with the type of elements that are stored in the array. Also, the name variable is read-only and attempting to change it will not change the element in the array itself.

Loop interrupt statements

There are three loop interrupt statements: break, return, and continue. The first two are capable of completely interrupting the loop, while continue only interrupts the current iteration. If you use it intentionally in your code endless loop Java, these operators must be present in it. Let's look at a simple example of using break:

Although in this for statement There are 11 iterations, only 8 will be executed, because when the counter i is equal to 7, the condition, in the body of which there is a break statement, will be triggered.

The return statement works in a similar way, with the difference that it not only provides exit from the Java loop, but also from the method in which the loop is placed.

Using break as goto

It should be borne in mind that break interrupts only the loop in the body of which it is directly located, i.e. if you use it in a nested loop, the outer loop will not stop running. To do this, the break statement can be used as a civilized form of goto.

In this version this operator used in conjunction with a label, which allows you to organize an exit not only from loops, but also from any block of code. A label is an appropriately named identifier followed by a colon. The label is declared at the beginning of the code block being marked. To interrupt execution of a marked block, in the right place must be declared: break label_name. Consider the example in the figure below:

The code declares three blocks with label names One, Two and Three, respectively. The break statement labeled Two is nested in all three blocks, but when it fires, the program will exit blocks Three and Two and continue execution in block One. Those. in the console we will see two messages: Three and One.

Conclusion

We learned about the concept of loops in Java, the main while and for statements, and their do-while and for each forms, respectively. For a better understanding, we recommend doing exercises using these operators in various forms, and also in various ways their interruption and transition from one block to another.

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. IN Java language There are the following types of cycles:

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 could be anyone else 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 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 in a cycle checking in progress, whether the array element is greater than 10, then 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 also won’t see last element, which is less than 10. Now let's make sure that if the number is greater than 10, the loop does not end, but simply moves 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.

Like almost any programming language, Java has tools designed to repeat a specific piece of code over and over again. Such tools are usually called cycles. In Java, loops are represented by statements such as while and for and their variations. Loops are typically used to traverse one-dimensional and multi-dimensional arrays and data structures to find specific elements and further operate on them. But this is not the only way to use a tool such as the Java loop. Examples of use will be provided as we review them.

Java while loop: description and examples

While is the fundamental loop operator in Java. The code fragment enclosed in its body will be repeated until the condition of the expression enclosed in parentheses after it satisfies the true value. while statement V general view has the following form: while (condition)(//loop body). Once the Boolean condition is no longer true, the code enclosed in the loop body will stop executing. Control will be transferred to the line that comes immediately after it. If the body of the loop contains only one statement, then you can omit the curly braces. However, among programmers it is considered good form to always set them. Let's look at an example:

Public class whileDemo (

System.out.println (“Printing Numbers from 1 to 10”);

while (count<=10) {

System.out.println(count);

The initially declared variable count has the value 1. Next we see a logical expression, which is enclosed in parentheses after the name of the operator. If the value is true, the loop will return true until the value of the count variable is equal to or less than 10. With each pass or iteration, the value of the variable will be incremented by 1 and printed to the console screen. When the value of the variable reached the value 11, the loop terminated. If the value of the count variable was initially equal to 11, then the loop condition would be false. The program wouldn't even enter the body. It should be noted that Java syntax allows you to use a While statement without a body. Consider the following example. Let's say you have two variables: i=100 and j=200. We are faced with the task of calculating their arithmetic mean programmatically; for this purpose we can use a “hollow” while loop:

While(++i<- — j);

As a result of this operation, the value of any of these two variables will be equal to the average of their initial values. As you can see in this example, the loop worked fine without a body and performed all the necessary actions in the conditional expression.

do-while loop

In the previous examples, if the condition expression returned false, the program ignored the body of the loop and continued further execution. But sometimes situations arise when the code contained in the body of the loop must be executed at least once, regardless of the truth of the condition expression. In other words, sometimes it happens that you need to check the truth of a conditional expression at the beginning, rather than at the end of the loop. A variation of the while loop, code-named do-while, can provide similar functionality. It has the following form: do (//loop body) while (condition). As you can see, first the body of the loop is executed here, and then the truth of the condition is checked. This is done at every iteration. The above code will work approximately the same as in the case of while. But if we set count to 11, the body of the loop would still be executed once before the statement could test the truth of the expression.

Examples and description: for – Java loop

The for loop is a universal and efficient language form in the Java language. Up until version 5 of the JavaSDK, there was only one traditional form of the for statement. After it, a new one appeared - foreach. This section will focus on the traditional form of the operator. The for loop in Java looks like this:

for (inti=0; i<10; i++) {//Loop statements to be executed

Before control is transferred to the code at the end of the loop, the variable i is initialized, which acts as a counter. Next, you need to check the conditional expression in which the counter was compared with a specific value. If the program returns true, the body of the loop is executed. In this case, the counter value changes by a predetermined step and the conditional expression is checked again. This happens until the condition becomes false. For better understanding, here is an example of how a Java for loop works.

public class ForLoops (

public static void main (String args) (

intend_value =11;

for ; //create an array of type “something” of n elements

for(int i = 0; i< n; i++){

array[i] = new Something(); //create “something” and put it in an array

}

How to break out of a Java loop

To exit a loop, there are the keywords break - “interrupt”, continue - “resume” and return - “return”. The break command switches the program to execute the statements following the loop. Loop interruption conditions in Java are formalized through if-branching. The main thing is that the check is performed before the main part of the loop body.

//after creating array m we write:

for (a: m) (

if (a==5) break;

System.out.println(a);

}

Branch and loop operators in Java often work together: we start a loop, and inside it we check to see if a condition has not yet been met under which we need to interrupt the loop or do something else.

If you use break in a nested loop, only that loop will be interrupted, while the outer loop will continue to execute.

To terminate a for loop iteration early in Java, continue is used. When the program reaches it, it skips the uncompleted part of the iteration, updates the counter, and moves on to the next iteration.

In while constructs, the same continue works differently: it returns us to checking the condition for continuing the loop. Another command, return, returns the program to the place where the method in which the loop is located was called.

Both continue and break can be used with a label - to jump to the desired part of the code - by analogy with goto:

breakMark1; //provided that Mark1 is somewhere above:

Java Infinite Loop

Creating an infinite loop is easy - just don't specify any parameters in the for:

for (; ;) ()

It's harder to take advantage of it. Typically, an infinite loop is a critical error that prevents the program from executing. Therefore, each loop should be checked for its ability to terminate correctly at the right time. To do this you need:

  • indicate interrupt conditions in the body of the loop,
  • make sure that the variable in the interrupt condition can take a value at which the loop will be stopped.