Groovy Control Flow: Conquering Decisions (if/else/switch) & Loops (for/while)

25 Jun 2023 Balmiki Mandal 0 Groovy

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.

Groovy
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.

 

Groovy
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.

 

Groovy
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.

 

Groovy
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.

 

Groovy
fruits = ["apple", "banana", "cherry"]
for (fruit in fruits) {
  println(fruit)
}

 

You can also use a range of numbers:

 

Groovy
for (i in 1..5) {
  println(i)
}

 


while loop: Executes a block of code as long as a condition remains true.

 

Groovy
count = 0
while (count < 3) {
  println("Loop iteration: $count")
  count++
}
By mastering these control flow structures, you can write Groovy programs that make informed decisions, repeat actions efficiently, and handle complex logic with ease.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.