Java for loop for arrays. Infinite for (Java) loop

Latest update: 31.10.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 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.

Since JDK 5, there are two forms in Java for loop. The first is the traditional form, used since the original Java versions. Second - new form“for-each”. We'll look at both types of for loops, starting with the traditional form.

General form traditional operator for looks like this:

If only one statement will be repeated in a loop, you can omit the curly braces.

Cycle for operates as follows. When the loop is started for the first time, the program executes initialization part of the cycle. In general, this is an expression that sets the value of a loop control variable, which acts as a counter that controls the loop. It is important to understand that the expression initialization executed only once. The program then calculates condition which should be boolean expression. Typically, the expression conditions compares the value of the control variable with target value. If this value is true, the program executes body cycle. If it is false, the loop execution is aborted.. The program then executes body loop and only after that the part is executed repetition cycle. Repetition it is usually an expression that increases or decreases the value of a control variable. The program then repeats the loop, each time it passes, first calculating conditional expression, then doing body loop and executing the expression repetitions . The process is repeated until the value of the expression conditions will not become false.

Since most loops only use their variables within the loop, the loop for allows the expression initialization was a complete variable declaration. Thus, the variable is limited to the body of the loop and is invisible from the outside.

Here are a couple of examples that explain all of the above:

In this example the variable i declared outside the loop (line 7), so it is also available after its completion (line 12).

From the output of this program it can be seen that the expression repetitions cycle, namely the prefix increment ( ++i) variable i executed after the body of the loop has been executed, that is, after line 10 has been executed, which prints the greeting.

This point is very important to understand in order to have a correct understanding of how the cycle works. for.

Now let's look at the output of this program with and without command line arguments:

As can be seen from the output of this program, the increment of the variable i occurs after execution last command loop that prints the greeting (line 10).

Now let’s declare a variable inside the loop (for statement):

As you can see, Eclipse immediately pointed out to us the error that the variable j, declared on line 15, is not visible outside the loop because its scope, or scope, extends only to the body of the loop in which it was declared.

For the program to work, you need to comment out line 19.

The output of this code is similar to the output of the code we just looked at, except that instead of “Hello,” it outputs “Hello.” Well, after the loop it’s not possible to display the value of a variable j.

When declaring a variable inside a loop for it is necessary to remember the following important circumstance: the area and lifetime of this variable completely coincide with the area and lifetime of the operator for .

Loop Syntax for is not limited to loops with a single variable. As in the expression initialization , and in the expression repetitions can be used comma to separate multiple expressions initialization And repetitions .

For example:

In this example in initialization part of the loop we set the initial values ​​of both control variables a And b. Both comma separated statements in iterative parts are executed each time the loop is repeated.

This code generates the following output:

Cycle for supports several flavors that enhance its capabilities and applicability. The flexibility of this cycle is due to the fact that its three parts: initialization , checking conditions And iterative does not have to be used only for its intended purpose. In fact, each of the sections of the statement for can be used for any purpose. For example:

The example is of course a little puzzling, but in essence it is simple. The first part of the statement initializes the variable b, the second checks it, and the third displays a message on the console.

Essentially this program does the same thing of greeting arguments if they exist. If they are not there, then it does not output anything. Let me immediately give an example of its output:

As can be seen from the output of this program, the iteration part is executed, as already mentioned, after the loop body is executed. In this case it is the operator println on line 9. The for statement in this code stretches across two lines 9 and 10 because it is quite long. I did this to demonstrate that each part of the for statement can be used for different purposes. It is also worth noting that the increment of the variable i occurs on line 12 and also sets a condition for continuing or exiting the loop, which is checked in line 9.

Another similar example, a for loop can be used to iterate through the elements of a linked list:

It is also worth noting that any part of the cycle for (initialization, condition And iterative) or you can even skip everything. For example, you can create an infinite loop this way:

( ;; ){
//endless loop
}

An initialization or iteration expression, or both, may be missing:

In this example initialization And iterative expressions are moved outside the definition of the operator for. As a result, the corresponding parts of the statement for empty.

To make the sequence of execution of the parts of the for statement more clear, I will give a small example. Although we have not studied the methods yet, I hope the idea of ​​this program will be understood by you. Its purpose is to clearly show the sequence of execution of all parts of the for statement.

From the output of the program it is clear that initialization part of the program ( initTest() method) is executed only once.

Then the check is performed conditions , represented by the method condTest().

After checking conditions , is executed body cycle.

And after that the part is executed repetition , represented by the method recTest().

The condTest() method checks the loop continuation condition. In this case, the variable i is compared with 4, and as long as the variable i is less than 4, the body of the loop is executed.

The body of the loop is executed four times since the variable i was initialized to zero by default.

Operator foreach

Starting with JDK 5, Java can use a second form of the for loop, which implements a loop in the style foreach (“for everyone”). Cycle in style foreach is intended for strictly sequential execution of repeated actions in relation to collections of objects, such as arrays. In Java, the ability to use a loop foreach implemented by improving the cycle for. General version form foreach cycle for has the following form:

for (iteration variable type: collection) block statements

Type this is the type of the variable, iteration variable — the name of an iterative variable that will sequentially take values ​​from collections , from first to last. The collection element specifies the collection over which to loop. With cycle for can be used various types collections, but for now we will only use arrays, which, by the way, have not yet been tested, but according to at least There have already been many examples with greetings from an array of strings where command line arguments go.

Note: operator foreach applies to arrays and classes that implement the java.lang.Iterable interface.

At each iteration of the loop, the program retrieves the next element of the collection and stores it in an iteration variable. The loop runs until all elements of the collection have been retrieved.

Although the cycle repeats for in style foreach is executed until all elements of the array (collection) have been processed; the loop can be interrupted earlier using the operator break.

Because an iteration variable receives values ​​from a collection, its type must match (or be compatible with) the type of the elements stored in the collection. Thus, when looping over arrays, the type must be compatible with the underlying type of the array.

To understand the motivation for using loops in the style foreach , consider the type of cycle for, which this style is intended to replace.

Let's take our example again of greeting arguments from the command line:

Isn't it much more elegant than using other loop operators for this purpose?

Actually, this program has a simple output:

We have already seen him many times in different options, but repetition is the mother of learning.

For complete clarity, let's look at a few more examples.

Each time the loop passes, the variable x is automatically assigned a value equal to the value of the next element in the nums array. Thus, on the first iteration x contains 1, on the second - 2, etc. This simplifies the program syntax and eliminates the possibility of going beyond the array.

The output of this part of the program is:

Although the cycle repeats for in style foreach is executed until all elements of the array have been processed; the loop can be interrupted earlier using the operator break. For example:

IN in this example the loop will run only three iterations, after which the loop will exit according to the operator’s condition if, which will trigger the operator break.

It is also important to understand that the iteration variable receives values ​​from the collection (array) at each iteration, therefore, even if its value is changed in the body of the loop, then at the next iteration it will again take the next value from the collection. Moreover, its changes do not in any way affect the values ​​of the collection (array elements in this example).

This code will output the following:

Any method that returns an array can be used with foreach . For example class String contains a toCharArray method that returns a char array. Example:

This code will simply print out the string Hello World!

This is where we can finish with these operators. The only thing worth mentioning is that in the initialization part you can only declare variables of the same type, or you can initialize variables different types, but those that can be cast to one general type according to the type casting rule that we looked at earlier.

Finally, I’ll give a couple more examples of an advanced operator for. By and large, this is just a refactored code of the example that I already gave.

Isn't it true that this code has become more readable and understandable than the one I already provided? Or is it not clear? Well then, let's look at another example of code that does the same thing.

Isn't it clear again?

Both of these codes produce the same output:

Of course, provided that the arguments in command line there were Vasya and Petya.

On this with for operator and we will finish with its shadow foreach.

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 multidimensional arrays and data structures for finding certain elements and further operations with 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 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 )