Loops are used to repeatedly execute a block of code as long as a certain condition is true. Java provides several types of loops: 'for'
, 'while'
, and 'do-while'
.
- for Loop
The 'for'
loop is often used when the number of iterations is known in advance.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
- while Loop
The '
while'
loop is used when the number of iterations is not known in advance, and the loop continues as long as a certain condition is true.int i = 0;
while (i < 5) {
System.out.println("Iteration " + i);
i++;
}
- do-while Loop
The '
do-while
'
loop is similar to the while
loop, but it guarantees that the loop body is executed at least once, even if the condition is false initially.int i = 0;
do {
System.out.println("Iteration " + i);
i++;
} while (i < 5);
Loops can be used to iterate over arrays, collections, or perform repetitive tasks based on certain conditions
- for-each loop
The 'for-each' loop is a concise way to iterate over elements of an array, collection, or any object that implements the Iterable interface. It simplifies the syntax of iterating through elements and is especially useful when you don't need to know the index of the current element.
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
The break and continue statements are used to control the flow of loops. The break statement is used to exit a loop immediately, while the continue statement is used to skip the current iteration of the loop and move to the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Комментариев нет:
Отправить комментарий