4. Control Structures

If-Else

// Defining a variable 'number' and assigning it the value 5
def number = 5

// The 'if' statement checks if the number is divisible by 2 with no remainder
if (number % 2 == 0) {
    // This block executes if the number is even (i.e., divisible by 2)
    println "${number} is even"
} else {
    // This block executes if the number is not divisible by 2 (i.e., it's odd)
    println "${number} is odd"
}

For loop

// Groovy script with a traditional C-style for loop

// The 'for' loop starts here
for (int i = 0; i < 5; i++) { // Initialize 'i' to 0, run loop while 'i' is less than 5, increment 'i' after each loop
    println "Iteration ${i}" // Print the current iteration number, 'i', using Groovy's string interpolation
}

While loop

def count = 5

// Start of the while loop. It will run as long as 'count' is greater than 0.
while (count > 0) {
    // Print the current value of 'count' to the console.
    println "Count: ${count}"

    // Decrease the value of 'count' by 1.
    count--
}

[Hint: Don't forget to decrease the value of the variable count. Without this decrement, 'count' would always remain greater than 0, causing the loop to repeat indefinitely.]

Switch statement

def fruit = 'Apple'

// Start of the switch statement for the variable 'fruit'
switch (fruit) {
    // First case: if the fruit is 'Apple'
    case 'Apple':
        // Print a message to the console
        println 'Fruit is an apple.'
        // Exit the switch block after executing this case
        break
    // Second case: if the fruit is 'Banana'
    case 'Banana':
        // Print a message to the console
        println 'Fruit is a banana.'
        // Exit the switch block after executing this case
        break
    // Default case: if the fruit is neither 'Apple' nor 'Banana'
    default:
        // Print a message to the console
        println "Unknown fruit"
}

[Tip: The break keyword is crucial in preventing 'fall-through'. Without it, the program would continue executing the subsequent cases even after finding a match.]

[Tip: The default case is executed if no condition of the switch applies ]