The while statement is used when you want to automatically iterate a certain process. For example, if you want to output numbers from 1 to 100 to the console, writing System.out.println () 100 times will make the code redundant. Therefore, we use a while statement. As a flow of iterative processing ① Variable initialization ② Conditional expression ③ Repeated processing ④ Variable update From there again ② Conditional expression ③ Repeated processing ④ Variable update And repeat.
Main.java
while (conditions) {
Repeated processing;
}
You can use the while statement above to perform iterative processing. [Example]
Main.java
int x = 3;
while (x <= 3) [
System.out.println(x + "Rank");
x++;
}
The above defines the variable x with x = 3. x ++; adds 1 to x. Since 1 is added to the variable, the while condition becomes false at the 4th iteration, and the iteration process ends.
[Example]
Main.java
int x =5;
while (x > 0) [
System.out.println(x);
x--;
}
The above iterates when is greater than 0.
Along with the while statement, the for statement is one of the iterative processes. The flow of iterative processing is the same as the while statement ① Variable initialization ② Conditional expression ③ Repeated processing ④ Variable update From there again ② Conditional expression ③ Repeated processing ④ Variable update And repeat. for statement
Main.java
for (Variable initialization;Conditional expression;Variable update) {
System.out.println(Repeated processing);
}
[Example]
Main.java
for (int x = 1;x <= 10;x++) {
System.out.println(x);
}
If you write as above, the process will be repeated 10 times. If you use it, the for statement is easier to use. continue Break is used to end the iterative process, but continue skips only that lap and executes the next lap. [Example]
Main.java
for (int x = 1;x <= 10;x++) {
if(x%5==0) {
continue;
}
System.out.println(x);
}
Written as above, it ends the loop of multiples of 5 and executes the next loop.
Recommended Posts