Android java exit from loop. Loops in Java - how to create and break them

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 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 write conditional operator, which 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 ;

  1. public class CuclesInJava(

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

  2. 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.

for loop

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.

The general form of a traditional for statement is as follows:

for(initialization; condition; repetition)
( // body
}

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

The for loop works as follows. When the loop is launched for the first time, the program performs the initialization part of the loop. IN general case 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 initialization expression is executed only once. The program then evaluates the condition, which must be a Boolean expression. Typically, the expression compares the value of the control variable with target value. If this value is true, the program executes the body of the loop. If it is false, the loop execution is aborted. The program then performs the repeat portion of the loop. Typically this is an expression that increases or decreases the value of a control variable. The program then repeats the loop, each time it passes by first evaluating the conditional expression, then executing the body of the loop, and executing the repeat expression. The process is repeated until the repeat expression evaluates to false.

Below is a version of the clock counting program that uses a for loop.

// Demonstration of using a for loop.
class ForTick (

int n;
for(n=10; n>0; n-)

}
}

Declaring loop control variables inside a for loop

Often the variable that controls a for loop is needed only for that loop and is not used anywhere else. In this case, the variable can be declared inside the initialization part of the for statement. For example, the previous program can be rewritten by declaring a control variable of type int inside a for loop:

// Declaring a loop control variable inside a for loop.
class ForTick (public static void main(String args) (
//V in this case variable n is declared inside the for loop
for(int n=10; n>0; n-)
System.out.println("beat " + n) ;
}
}

When declaring a variable inside a for loop, you must remember the following important circumstance: the scope and lifetime of this variable is completely the same as the scope and lifetime of the for statement. (That is, the variable's scope is limited by the for loop.) Outside the loop for variable will cease to exist. If a loop control variable needs to be used in other parts of the program, it cannot be declared inside a for loop.

In cases where the loop control variable is not needed anywhere else, most Java programmers prefer to declare it inside a for statement. As an example, let's give a simple program, which checks whether the entered number is prime. Note that the loop control variable i is declared inside the for loop because it is not needed anywhere else.

Variations of the for loop

The for loop comes in several variations that increase its capabilities and applicability. The flexibility of this loop is due to the fact that its three parts: initialization, condition checking and iteration do not have to be used only for their intended purpose. In fact, each section of the for statement can be used for any purpose. Let's look at a few examples.

One of the most common variations involves the use of a conditional expression. In particular, this expression does not need to compare the loop's control variable with any target value. In fact, the condition driving a for loop can be any Boolean expression. For example, consider the following snippet:

boolean done = false;
for(int i=1; !done; i++) (
// ...
if(interrupted()) done = true;
}

In this example, the for loop continues until done is set to true. In this loop, the value of the loop control variable i is not checked.

Here's another variation of the for loop. By leaving all three parts of the statement empty, you can intentionally create an infinite loop (a loop that never ends). For example:

for(; ;) (
// ...
}

This loop can run indefinitely because there is no condition that would cause it to be interrupted. Although some programs such as command processors operating system, require an infinite loop, most "infinite loops" are really just loops with special conditions interrupts. As you'll soon see, there is a way to break a loop - even an infinite loop like this example - that doesn't require using a regular loop conditional.

The "for-each" version of the for loop

Starting with JDK 5, Java allows you to use a second form of the for loop, which implements a "for-each" style loop. As you may know, the concept of "for-each" loops is becoming increasingly common in modern programming language theory and is quickly becoming standard. functionality in many languages. A for-each style loop is designed to perform repeated actions on a collection of objects, such as an array, in a strictly sequential manner. Unlike some languages ​​like C#, which use "for-each" loops to implement keyword foreach, in Java, the ability to use a for-each loop is implemented by improving the for loop. The advantage of this approach is that no additional keyword is required to implement it, and no pre-existing code is broken. The for-each style for loop is also called an enhanced for loop. The general form of the "for-each" version of a for loop is next view:

for (type iter-per: collection)
block operators

Here type indicates the type, and iter-per is the name of the iteration variable that will sequentially take values ​​from the collection, from first to last. The collection element specifies the collection over which to loop. With a for loop you can use Various types collections, but in this chapter we will only use arrays. (Other types of collections that can be used with a for loop, such as those defined in the Collection Framework, are discussed in later chapters of the book.) At each iteration of the loop, the program retrieves the next element of the collection and stores it in the iter variable. The loop runs until all elements of the collection have been retrieved.

Because an iteration variable receives values ​​from a collection, the 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.

The for-each style for loop allows you to automate this process. In particular, the use of such a loop makes it possible not to set the value of the loop counter by specifying its initial and final values, and eliminates the need to manually index the array. Instead, the program automatically loops through the entire array, getting the values ​​of each of its elements sequentially, from the first to the last. For example, given the "for-each" version of the for loop, the previous fragment could be rewritten as follows:

int nums = ( 1, 2, 3, 4, 5, b, 7, 8, 9, 10 );
int sum = 0;
for(int x: nums) sum += x;

Each time the loop passes through the variable x is automatically assigned a value equal to next element array nums. Thus, at the first iteration x contains 1, at the second - 2, etc. This not only simplifies the program syntax, but also eliminates the possibility of array out-of-bounds errors.

Below is an example full program, illustrating the use of the described "for-each" version of the for loop.

// Using a for loop in for-each style.
class ForEach(
public static void main(String args) (

int sum = 0;
// use for-each style to display and sum values
for(int x: nums) (

sum += x;
}
System.out.println("The sum is: " + sum) ;
}
}

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
The amount is: 55

As you can see from this output, the "for-each" style for statement automatically loops through the array elements, from lowest index to highest index.

Although the for-each style for loop repeats until all elements of the array have been processed, the loop can be interrupted earlier by using a break statement. For example, next program sums the values ​​of the first five elements of the nums array.

// Usage break operator in a for loop in for-each style.
class ForEach2 (
public static void main(String args) (
int sum = 0;
int nums = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
// use a for loop to display and sum values
for(int x: nums) (
System.out.println("Value is: " + x) ;
sum += x; v if (x == 5) break; // terminate the loop after receiving 5 values
}
System.out.println("The sum of the first five elements is: " + sum);
}
}

The program generates the following output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
The sum of the first five elements is: 15

As you can see, the loop stops execution after receiving the value of the fifth element. The break statement can also be used with other Java loops. This operator will be discussed in more detail in subsequent sections of this chapter.

When using a for-each loop, there is one important thing to keep in mind: Its iteration variable is a read-only variable because it is associated only with the original array. The operation of assigning a value to an iterative variable has no effect on the original array. In other words, the contents of an array cannot be changed by assigning a new value to an iteration variable. For example, consider the following program:

// The for-each loop variable is read-only.
class NoChange (
public static void main(String args) (
int nums = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
for(int x: nums) (
System.out.print(x + " ");
x=x*10; // this operator has no effect on the nums array
}
System.out.println();
for(int x: nums)
System.out.print(x + " ");
System.out.println();
}
}

The first for loop increments the value of the iteration variable by 10. However, this assignment operation has no effect on the original nums array, as can be seen from the result of the second for statement. The output generated by the program confirms this:

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Iteration in multidimensional arrays

An improved version of the for loop also applies to multidimensional arrays. However, it should be remembered that in Java multidimensional arrays consist of arrays of arrays. (For example, a two-dimensional array is an array of one-dimensional arrays.) This is important when iterating in multidimensional array, since the result of each iteration is the next array, not a single element. Moreover, the type of the for loop iteration variable must be compatible with the type of the resulting array. For example, in case two-dimensional array iteration variable must be a reference to one-dimensional array. In general, when you use a for-each loop to iterate through an array of size N, the resulting objects will be arrays of size N-1. To understand what follows from this, consider the following program. It uses nested for loops to obtain row-ordered elements of a two-dimensional array.

// Using a for-each-style for loop on a two-dimensional array.
class ForEach3 (
public static void main(String args) (
int sum = 0;
int nums = new int ;
// assigning values ​​to the elements of the nums array
for (int i = 0; i nums[i] [j] = (i+l)*(j+l) ; // use a for-each style for loop to display
// and summing the values
for (int x : nums) (
for(int y: x) (
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Sum: " + sum);
}

This program generates the following output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Amount: 9 0

The following line of this program deserves special attention:

for (int x : nums) (

Pay attention to the way the variable x is declared. This variable is a reference to a one-dimensional array of integer values. This is necessary because the result of each iteration of the for loop is the next array in the nums array, starting with the array specified by the nums element. The inner for loop then iterates through each of these arrays, displaying the values ​​of each element.

Using an Improved For Loop

Since each for-each style for statement can only loop through the elements of an array sequentially, starting with the first and ending with the last, it may seem to be of limited use. However, it is not. Many algorithms require the use of this particular mechanism. One of the most commonly used algorithms is search. For example, the following program uses a for loop to search for a value in an unordered array. The search stops when the search value is found.

// Search the array using a for-each style for loop.
class Search (
public static void main(String args) (
int nums = ( 6, 8, 3, 7, 5, 6, 1, 4 );
int val =5;
boolean found = false;
// use for loop in for-each style
for (int x: nums) (
if (x == val) (
found = true;
break;
}
}
if(found)
System.out.println("Value found!");)

In this case, choosing the "for-each" style for the for loop is completely justified, since searching through an unordered array involves looking through each element sequentially. (Of course, if the array were ordered, binary search could be used, which would require a different loop style to implement.) Other types of applications that benefit from for-each loops include averaging, finding minimum or maximum value in a set, search for duplicates, etc.



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

General form of the traditional operator for as follows:

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 the 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 the last command in the loop is executed, which 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 time of existence 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 parts of the cycle we establish initial values 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 increase 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 there are any. 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 every part of the for statement can be used in 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 cycle
}

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 operator more clear, I will give 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 , performed 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 each"). 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 loop for You can use different types of collections, but for now we will only use arrays, by the way, which we haven’t tried yet, but at least there have already been many examples with greetings from an array of strings, where command line arguments go.

On a 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 condition of the operator 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 initialize variables different types, but such that can be reduced 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 by and large, this is just the 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 let's finish with its shadow foreach.

A loop is a block of commands that is executed over and over again as long as a certain condition is met. The repeated piece of code is called the "loop body". One execution of the loop body is called an iteration.

In Java, you can work with several types of loops - for this there are the following operators:

while– cycle with precondition– first we check the condition, then execute the body of the loop;

do... while– cycle with postcondition– first we execute the body of the loop once, then we check the condition and, if it is met, we continue;

for– loop with a counter – runs and updates the counter at each iteration as long as the condition in the loop declaration is met (i.e., checking the condition returns true);

abbreviated for(known as foreach in other languages) – iterates through the array from the first element to the last and executes the body of the loop at each iteration.

The essence of the loop condition is checking an expression with one or more variables: “While a<11, в каждой итерации выполняем тело цикла и увеличиваем "а" на 1». Но чему равно «а» при первом выполнении цикла?

If we use constructs with while, the value must be specified before the start of the loop:

int a = 1;

while (a< 11) {

System.out.println(a);

a++; //increase a by one

}

If the variable works as a loop counter and is not used outside of it, it is initialized directly in the condition. And then they write what to do with it at the end of each iteration. All this - in one line - using for:

for (a=1, a<11, i++) {

System.out.println(a);

}

We get the same result. The list could start from zero or from a negative value - we determine the range ourselves.

The shortened version of the for loop contains no indication of the number of repetitions or actions at the end of the step. A foreach loop is used to iterate through arrays. You need to move from the first element to the next until the array ends.

int ms = ( 1, 2, 3, 4); //create an array

int s = 0;

for(int i: ms) ( //specify what to iterate

s *= i; //consistently multiply the elements

}

System.out.println(s);

Java Nested Loops

Loops can be nested one within the other. In this case, the number of repetitions of the outer and nested loops is multiplied. If the outer one is to be executed 5 times and the inner one 5 times, the loop will be executed 25 times in total.

Let's display the multiplication table using two arrays:

int a, b, result = 0;

for (a = 2; a< 10; a++) {

for (b = 2; b< 10; b++) {

result = a*b;

System.out.println(a+"x"+b+" = "+result);

}

}

Creating Objects in a Java Loop

Loops are useful when you need to create and number many objects. Their number is sometimes unknown in advance: objects can be created at the user's request. So we asked how much something was needed and wrote the number into the variable n. Now let's create objects in the required quantity:

Something array = new Something[n]; //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 - similar to 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 the value at which the loop will be stopped.

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 until 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 falls out, it cannot simply be replaced with some other number, for example, with 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 in 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 be immediately 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 loop 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.