for
, while
, do-while
in GroovyGroovy, like many other programming languages, provides various looping constructs that allow you to execute a block of code multiple times based on certain conditions. The three main types of loops in Groovy are for
, while
, and do-while
. These loops are used to repeat actions, making them fundamental to control flow in programming.
Below is a detailed explanation of these loops in Groovy.
for
LoopThe for
loop is used when you know the number of iterations beforehand. It allows you to repeat a block of code a fixed number of times. In Groovy, the for
loop has two common forms:
for
loop:The basic for
loop structure in Groovy works like in other languages, with initialization, condition, and increment.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example:
for (int i = 0; i < 5; i++) {
println "Iteration number: $i"
}
Here, the loop will print the iteration number from 0 to 4. The loop runs as long as the condition i < 5
is true. After each iteration, i
is incremented by 1.
for
loop (foreach loop):Groovy provides an enhanced for
loop to iterate through collections (arrays, lists, etc.) in a more readable way.
Syntax:
for (item in collection) {
// Code to be executed
}
Example:
def numbers = [1, 2, 3, 4, 5]
for (num in numbers) {
println "The number is: $num"
}
Here, the loop iterates over each item in the numbers
list and prints it.
while
LoopThe while
loop is used when you want to repeat a block of code as long as a specified condition is true. The condition is checked before each iteration.
Syntax:
while (condition) {
// Code to be executed
}
Example:
int i = 0
while (i < 5) {
println "Current value of i: $i"
i++
}
In this example, the loop will continue to execute as long as the condition i < 5
remains true. After each iteration, i
is incremented by 1.
do-while
LoopThe do-while
loop is similar to the while
loop, but with one key difference: the condition is checked after the code block executes. This means the code block will run at least once, even if the condition is false from the start.
Syntax:
do {
// Code to be executed
} while (condition)
Example:
int i = 0
do {
println "Current value of i: $i"
i++
} while (i < 5)
Here, the loop will print the value of i
from 0 to 4. The condition i < 5
is checked after each iteration, so the loop will run until i
reaches 5.
for
loop: Used when the number of iterations is known beforehand. It can be used for iterating over collections as well.while
loop: Executes the block of code as long as the condition is true. The condition is checked before entering the loop body.do-while
loop: Executes the block of code at least once and then checks the condition. The condition is checked after the code block is executed.These looping structures are essential for managing repetitive tasks and implementing efficient algorithms in Groovy programs.
Read more