Show List
Control structures
Control structures are statements that determine the flow of execution of a program. They allow the programmer to specify the conditions under which certain parts of the code should be executed.
Groovy provides several control structures that can be used to control the flow of execution in a program. These control structures include:
- If-Else: The if-else statement is used to execute a block of code if a certain condition is true, otherwise, another block of code will be executed.
Example:
goCopy codedef num = 10 if (num > 0) { println("num is positive") } else { println("num is negative") }
- Switch: The switch statement is used to choose from a number of cases based on the value of an expression.
Example:
goCopy codedef day = 3 switch (day) { case 1: println("Monday") break case 2: println("Tuesday") break case 3: println("Wednesday") break default: println("Invalid day") }
- For Loop: The for loop is used to execute a block of code a specified number of times.
Example:
cssCopy codefor (int i = 0; i < 5; i++) { println(i) }
- While Loop: The while loop is used to execute a block of code as long as a specified condition is true.
Example:
scssCopy codedef count = 0 while (count < 5) { println(count) count++ }
- Do-While Loop: The do-while loop is similar to the while loop, but the block of code is executed once before the condition is checked.
Example:
javaCopy codedef count = 0 do { println(count) count++ } while (count < 5)
These are the basic control structures in Groovy, and they can be used to control the flow of execution in a program and perform different actions based on different conditions.
Leave a Comment