For those who have just started learning programming including the Java language, and those who have already learned it, for review This time, I am writing to learn about ** iterative processing and iterative control statements **.
[Introduction to Java Table of Contents] -Variables and types ・ Type conversion -Variable Scope -String operation -Array operation ・ Operator ・ Conditional branch ・ Repeat processing ← Now here ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handling ・ About lambda expression ・ About Stream API
It is to repeat a certain process by specifying the number of times and while the condition is satisfied
.
python
int a = 0;
System.out.println("a => " + a);
a += 1;
System.out.println("a => " + a);
a += 1;
System.out.println("a => " + a);
It is possible to clearly describe a series of processes such as outputting a as described above, +1 and outputting again by iterative processing.
Iterative processing is also called ** loop **, and this article deals with while statement, do-while statement, for statement, and extended for statement
.
** While the specified condition is met (true) **, the process is repeated.
syntax
while(Conditional expression) {
Process statement; //Executed if the conditional expression is true
}
The conditional expression after while must be an expression that returns a boolean value (true, false)
.
While statement example
int num = 0;
while(num < 5) {
System.out.println("num => " + num);
num++;
}
Execution result
num => 0
num => 1
num => 2
num => 3
num => 4
It is possible to clearly describe a series of processes such as outputting the variable that appeared at the beginning, +1 and outputting again.
This process is repeated while num is less than 5,
when ** num incremented per loop becomes 5, **,
Since false is returned when the condition is judged, the while statement ends.
The iterative process may continue to be executed without stopping. Please note the following points.
Infinite loop example 1
int num = 0;
while(num < 5) {
System.out.println("num => " + num);
num++;
}
If there is no description of num ++
in this code, the num variable remains 0.
The conditional expression num <5
keeps returning true, resulting in a ** infinite loop **.
Infinite loop example 2
int num = 0;
while(true) {
System.out.println("num => " + num);
num++;
}
Next, if you do while (true)
in the conditional expression.
This is also always returned as true, resulting in a ** infinite loop **.
The ** repeat control statement ** used to prevent an infinite loop (to get out of the loop) will be explained in a separate article. Let's remember that as well.
Bad example
while(false) {
//processing
}
If the conditional expression is while (false)
, a compile error will occur because the process cannot be started.
There are times when nothing is output even though no error occurs.
Example of no output
int num = 0;
while(num > 0) {
System.out.println("num => " + num);
num--;
}
No output of the above execution result is output. This is because we are comparing whether the while condition is greater than 0, so false is suddenly returned and the process ends without entering the loop.
If the num variable is set to 1 or more, the processing inside the loop will be executed.
Improvement plan
int num = 3;
while(num > 0) {
System.out.println("num => " + num);
num--;
}
Execution result
num => 3
num => 2
num => 1
Similar to the while statement, iterates over ** while the specified condition is met (true) **.
syntax
do {
Process statement;
}while(Conditional expression);
Like the while statement, the conditional expression must be an expression that returns a boolean value (true, false)
.
do-While statement example
int num = 0;
do {
System.out.println("num => " + num);
num++;
}while(num < 5);
Execution result
num => 0
num => 1
num => 2
num => 3
num => 4
This process is repeated while num is less than 5,
when ** num incremented per loop becomes 5, **,
The do-while statement ends because false is returned when the condition is judged.
The timing at which the condition judgment is performed is different.
In the while statement, the condition is judged ** first **, so the process may not be executed as described above. However, in the do-while statement, there is a do block before the condition judgment **, and the condition judgment is performed after **. Therefore, the process is executed once regardless of the conditions.
Example of condition judgment_while
int num = 0;
while(num > 0) {
System.out.println("while_num => " + num);
num--;
}
Nothing is output in the above while statement.
Example of condition judgment_do-while
int num = 0;
do {
System.out.println("do-while_num => " + num);
num--;
}while(num > 0);
Execution result
do-while_num => 0
In the do-while statement, the process is executed only once, and the do-while statement ends because the conditional expression is false.
Note that there are such differences.
If there is only one statement that processes both the while statement and the do-while statement, it is possible to omit {}
.
In the case of while
int num = 0;
while (num < 5) System.out.println("num => " + num++);
Execution result
while_num => 0
while_num => 1
while_num => 2
while_num => 3
while_num => 4
do-In the case of while
int num = 5;
do
System.out.println("do-while_num => " + num--);
while(num > 0);
Execution result
do-while_num => 5
do-while_num => 4
do-while_num => 3
do-while_num => 2
do-while_num => 1
The for statement also repeats the process while the condition judgment is true.
In the while statement and do-while statement, only the conditional expression was described in ()
,
In the ()
of the for statement, ** declare the count variable, initialize it **, ** conditional expression **, and ** update the count variable **.
syntax
for(Equation 1;Equation 2;Equation 3;) {
Process statement;
}
The flow of the for statement is as follows.
-Declare and initialize a variable (counter variable) that indicates the number of repetitions in Equation 1. ・ Condition is judged by Equation 2. -If the condition judgment is true, the processing statement is executed. -After the process is executed, the counter variable is updated by Equation 3. ・ The condition is judged again by Equation 2. -If the judgment in Equation 2 is false, the for statement ends.
Let's actually see the code and the execution result.
For statement example
for(int i = 0; i < 5; i++) {
System.out.println("i => " + i);
}
Execution result
i => 0
i => 1
i => 2
i => 3
i => 4
In this way, the for statement can also describe the same processing as the while statement and do-while statement.
The for statement is also executed by the following description method.
Omitted description method of for statement_Example 1
int num = 0;
for(; num < 5; num++) {
System.out.println("num => " + num);
}
Execution result
num => 0
num => 1
num => 2
num => 3
num => 4
Instead of declaring and initializing the counter variable with the for statement, it is done in advance. It also works with this description method.
Omitted description method of for statement_Example 2
for(int num = 0; num < 5; ) {
System.out.println("num => " + num++);
}
Execution result
num => 0
num => 1
num => 2
num => 3
num => 4
The num variable is incremented and updated in the processing statement. It also works with this description method.
Note that if you forget to increment, you will end up in an ** infinite loop **.
There are some rules about how to write in the ()
of the for statement, so let's see.
The following will result in an error because only the variables are described in Equation 1.
Compile error
int num = 1;
for(num; num < 5; num++) {
System.out.println("num => " + num);
}
Equation 1 must be a statement, as shown below.
Improvement plan
int num = 1;
for(num += 1; num < 5; num++) {
System.out.println("num => " + num);
}
Execution result
num => 2
num => 3
num => 4
The following will result in an error because the multiple declaration expression is described in Expression 1.
Compile error
for(int i = 0, int = j = 0; i < 5; i++) {
System.out.println("i => " + i);
System.out.println("j => " + (j+=2));
System.out.println("===============");
}
There must be only one declarative expression in Equation 1 as shown below.
Improvement plan
for(int i = 0, j = 0; i < 5; i++) {
System.out.println("i => " + i);
System.out.println("j => " + (j+=2));
System.out.println("===============");
}
Execution result
i => 0
j => 2
===============
i => 1
j => 4
===============
i => 2
j => 6
===============
i => 3
j => 8
===============
i => 4
j => 10
===============
By separating the expressions with commas, you can enter multiple counter variable update processes. Let's rewrite the above code.
Example of putting multiple in equation 3
for(int i = 0, j = 2; i < 5; i++, j+=2) {
System.out.println("i => " + i);
System.out.println("j => " + j);
System.out.println("===============");
}
Execution result
i => 0
j => 2
===============
i => 1
j => 4
===============
i => 2
j => 6
===============
i => 3
j => 8
===============
i => 4
j => 10
===============
You can output the same result.
As a description method that makes the for statement even more convenient, it is used when all the elements of an array or collection are taken out in order and processed.
syntax
for(Variable declaration:Reference variable name) {
Process statement;
}
Let's actually see the code and the execution result.
Example of extended for statement
int[] numbers = {1, 2, 3, 4, 5};
for(int val : numbers) {
System.out.println(val);
}
Execution result
val => 1
val => 2
val => 3
val => 4
val => 5
The flow of assigning the elements of numbers to the val variable one by one and outputting
is repeated.
Let's describe the same process with a for statement and compare.
For statement
int[] numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] => " + numbers[i]);
}
Execution result
numbers[0] => 1
numbers[1] => 2
numbers[2] => 3
numbers[3] => 4
numbers[4] => 5
By describing in the extended for statement, it is not necessary to declare the counter variable, initialize or conditional expression, and describe the counter variable update process. It can be described more simply than the for statement.
The type you declare a variable must match the type of the referenced variable. The following will result in an error.
Compile error
String[] names = {"Tanaka", "Sato", "Suzuki"};
for(int val : names) {
System.out.println("name => " + val);
}
This is because the reference variable is an array of type String, whereas the variable declaration is of type ʻint`.
Be careful to match the types of the reference variable and the variable that receives each element.
Improvement plan
String[] names = {"Tanaka", "Sato", "Suzuki"};
for(String val : names) {
System.out.println("name => " + val);
}
Execution result
name =>Tanaka
name =>Sato
name =>Suzuki
** If there is only one statement to process both the for statement and the extended for statement, it is possible to omit {}
. ** **
For statement
for(int i = 0; i < 3; i++)
System.out.println("i => " + i);
Execution result
i => 0
i => 1
i => 2
For extended for statement
int[] numbers = {10, 20, 30};
for(int val : numbers)
System.out.println("val => " + val);
Execution result
val => 10
val => 20
val => 30
** Local variable type inference (var) is available. ** ** (I will summarize local variable type inference in another article.)
For statement
for(var i = 0; i < 3; i++) {
//abridgement
}
For extended for statement
for(var val : numbers) {
//abridgement
}
The iterative process described above was that ** the conditional expression would continue to be executed while it was true **.
When you want to exit the iterative process under specific conditions, use the iterative control statements ** break statement ** and ** continue statement **.
It is used to break out of the iterative process being executed and to get out of the infinite loop of the repeated statement. It is also used in the case of the switch statement.
After exiting the loop, do the following:
Break statement example
for(int i = 0; ; i++) {
if(i == 5) {
break;
}
System.out.println("i => " + i);
}
System.out.println("Processing after the for statement");
Execution result
i => 0
i => 1
i => 2
i => 3
i => 4
Processing after the for statement
There is no conditional expression because I forgot to write expression 2. Therefore, it becomes an infinite loop.
However, because there is a break;
in the block of ʻif (i == 5)`, it will break the loop when ** i becomes 5. ** **
And the processing after the for statement is executed.
It is used when the conditional expression is judged and the iterative process is continued by skipping only the process instead of interrupting the iterative process being executed.
Example of continue statement
for(int i = 0; i < 10; i++) {
if((i % 3) == 0) {
continue;
}
System.out.println("i => " + i);
}
System.out.println("Processing after the for statement");
Execution result
i => 1
i => 2
i => 4
i => 5
i => 7
i => 8
Processing after the for statement
By having continue;
in the block of ʻif ((i% 3) == 0)`,
** i is divided by 3 and processing is skipped when the remainder is 0. (The loop continues as long as the condition judgment in Equation 2 is true) **
Then, after the for statement ends, the subsequent processing is executed.
When the iterative statement is nested (if there are multiple), the break statement and continue statement described in the inner iterative statement are applied only to the inner iterative process. If you want to get out of the outer loop or skip it, you can use the ** label **.
syntax
Label name:
for(Equation 1;Equation 2;Equation 3;) {
for(Equation 1;Equation 2;Equation 3;) {
break or continue label name;
}
}
Let's see how the processing differs depending on the presence or absence of labels in the break statement and continue statement.
If the label is not used, it will be as follows. I want to end the loop when i and j are 1. It is implemented on the assumption that.
No label
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.println("i: " + i + ", j: " + j);
if(i == 1 && j == 1) {
break;
}
}
}
Execution result
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
The loop never ends, i is incremented to go to the next loop.
If you use a label, it will be as follows.
With label
loop:
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.println("i: " + i + ", j: " + j);
if(i == 1 && j == 1) {
break loop;
}
}
}
Execution result
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
When i and j are 1, the outer loop can also be exited.
If the label is not used, it will be as follows. When i and j are 1, I want to skip to the next loop that increments i. It is implemented on the assumption that.
No label
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == 1 && j == 1) {
continue;
}
System.out.println("i: " + i + ", j: " + j);
}
}
Execution result
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
It is skipped only when i and j are 1.
If you use a label, it will be as follows.
With label
loop2:
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == 1 && j == 1) {
continue loop2;
}
System.out.println("i: " + i + ", j: " + j);
}
}
Execution result
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
When i and j are 1, you can skip to the next loop that increments i.
By using labels in this way, it is possible to get out of multiple loops or skip them
.
I learned the syntax for repeating the same process and the iterative control statement for interrupting or skipping the process depending on the conditions. By using them properly, you can write the code clearly, and you don't have to write the same process many times, so I want to master it.
** [Introduction to Java] Let's master iterative processing! (for and while) ** ** Extended for statement (for-each statement) **
Recommended Posts