Intern
Quali tipi di cicli conosci?
sobes.tech AI
Risposta dell'AI
In Java, there are three main types of loops:
-
forloop: Used when the number of iterations is known in advance.// Classic for loop for iterating over a range of numbers for (int i = 0; i < 10; i++) { System.out.println(i); }There is also the enhanced for loop (for-each), which is convenient for iterating over collections and arrays.
// Enhanced for loop for iterating over an array String[] names = {"Alice", "Bob"}; for (String name : names) { System.out.println(name); } -
whileloop: Used when the number of iterations is not known in advance, and the condition is checked before each iteration.// while loop int count = 0; while (count < 5) { System.out.println("Iteration: " + count); count++; } -
do-whileloop: Similar towhile, but the condition is checked after executing the loop body, ensuring at least one iteration.// do-while loop int num = 5; do { System.out.println("Number: " + num); num--; } while (num > 0);
Additionally, there are break and continue statements to control the flow of loops.
break- Interrupts the execution of the current loop.continue- Skips the rest of the current iteration and proceeds to the next.