Control structures are fundamental in any programming language as they allow you to control the flow of your program. In Groovy, control structures are similar to those in Java, but with some enhancements and syntactic sugar that make them more concise and expressive.

  1. If-Else Statements

The if-else statement is used to execute a block of code based on a condition.

Syntax

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

Example

def age = 18

if (age >= 18) {
    println("You are an adult.")
} else {
    println("You are a minor.")
}

Explanation

  • The if statement checks if the age is greater than or equal to 18.
  • If the condition is true, it prints "You are an adult."
  • Otherwise, it prints "You are a minor."

  1. Switch Statement

The switch statement allows you to execute one block of code among many based on the value of a variable.

Syntax

switch (variable) {
    case value1:
        // code to be executed if variable == value1
        break
    case value2:
        // code to be executed if variable == value2
        break
    default:
        // code to be executed if variable doesn't match any case
}

Example

def day = "Monday"

switch (day) {
    case "Monday":
        println("Start of the work week.")
        break
    case "Friday":
        println("End of the work week.")
        break
    default:
        println("Midweek day.")
}

Explanation

  • The switch statement checks the value of day.
  • If day is "Monday", it prints "Start of the work week."
  • If day is "Friday", it prints "End of the work week."
  • For any other value, it prints "Midweek day."

  1. For Loop

The for loop is used to iterate over a range of values or a collection.

Syntax

for (variable in range) {
    // code to be executed for each value in range
}

Example

for (i in 1..5) {
    println("Number: $i")
}

Explanation

  • The for loop iterates over the range from 1 to 5.
  • For each value of i, it prints "Number: $i".

  1. While Loop

The while loop executes a block of code as long as a condition is true.

Syntax

while (condition) {
    // code to be executed as long as condition is true
}

Example

def count = 1

while (count <= 5) {
    println("Count: $count")
    count++
}

Explanation

  • The while loop checks if count is less than or equal to 5.
  • If true, it prints "Count: $count" and increments count by 1.
  • The loop continues until count is greater than 5.

  1. Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once.

Syntax

do {
    // code to be executed
} while (condition)

Example

def count = 1

do {
    println("Count: $count")
    count++
} while (count <= 5)

Explanation

  • The do-while loop executes the block of code first.
  • Then it checks if count is less than or equal to 5.
  • If true, it repeats the loop.

Practical Exercises

Exercise 1: If-Else Statement

Write a Groovy script that checks if a number is positive, negative, or zero.

Solution

def number = -5

if (number > 0) {
    println("The number is positive.")
} else if (number < 0) {
    println("The number is negative.")
} else {
    println("The number is zero.")
}

Exercise 2: Switch Statement

Write a Groovy script that prints the name of the month based on a given number (1-12).

Solution

def monthNumber = 3

switch (monthNumber) {
    case 1:
        println("January")
        break
    case 2:
        println("February")
        break
    case 3:
        println("March")
        break
    case 4:
        println("April")
        break
    case 5:
        println("May")
        break
    case 6:
        println("June")
        break
    case 7:
        println("July")
        break
    case 8:
        println("August")
        break
    case 9:
        println("September")
        break
    case 10:
        println("October")
        break
    case 11:
        println("November")
        break
    case 12:
        println("December")
        break
    default:
        println("Invalid month number.")
}

Exercise 3: For Loop

Write a Groovy script that prints the first 10 even numbers.

Solution

for (i in 1..10) {
    println("Even number: ${i * 2}")
}

Exercise 4: While Loop

Write a Groovy script that prints the numbers from 10 to 1 in descending order.

Solution

def count = 10

while (count >= 1) {
    println("Count: $count")
    count--
}

Exercise 5: Do-While Loop

Write a Groovy script that prints the numbers from 1 to 5 using a do-while loop.

Solution

def count = 1

do {
    println("Count: $count")
    count++
} while (count <= 5)

Conclusion

In this section, we covered the basic control structures in Groovy, including if-else statements, switch statements, for loops, while loops, and do-while loops. These constructs are essential for controlling the flow of your programs and making decisions based on conditions. Practice the exercises provided to reinforce your understanding and prepare for more advanced topics in Groovy.

© Copyright 2024. All rights reserved