Groovy Control Flow: Conquering Decisions (if/else/switch) & Loops (for/while)
Groovy Control Flow: Conquering Decisions (if/else/switch) & Loops (for/while)
Groovy, like many programming languages, provides powerful control flow structures to guide the execution of your code. These structures allow you to make decisions based on conditions and repeat actions as needed. In this guide, we'll explore Groovy's tools for conquering decisions and loops.
Conquering Decisions: if, else, and switch
if statement: The fundamental decision-making tool. It evaluates a condition and executes a block of code if the condition is true.
age = 25
if (age >= 18) {
println("You are eligible to vote!")
}
else statement: Pairs with if to provide an alternative block of code if the condition is false.
age = 16
if (age >= 18) {
println("You are eligible to vote!")
} else {
println("Sorry, you must be 18 or older to vote.")
}
else if statement: Lets you chain multiple conditions for more complex decision-making.
score = 85
if (score >= 90) {
println("Excellent work! You got an A!")
} else if (score >= 80) {
println("Great job! You got a B!")
} else {
println("Keep practicing! You got a C.")
}
switch statement: Provides a cleaner way to handle multiple conditions that check for a single variable's value.
grade = 'B'
switch (grade) {
case 'A':
println("Excellent work!")
break
case 'B':
println("Great job!")
break
case 'C':
println("Keep practicing!")
break
default:
println("Invalid grade.")
}
Mastering Repetitions: for and while loops
for loop: Used for iterating over a collection (like a list) or a range of values.
fruits = ["apple", "banana", "cherry"]
for (fruit in fruits) {
println(fruit)
}
You can also use a range of numbers:
for (i in 1..5) {
println(i)
}
while loop: Executes a block of code as long as a condition remains true.
count = 0
while (count < 3) {
println("Loop iteration: $count")
count++
}