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:

  1. 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:

go
Copy code
def num = 10 if (num > 0) { println("num is positive") } else { println("num is negative") }
  1. Switch: The switch statement is used to choose from a number of cases based on the value of an expression.

Example:

go
Copy code
def day = 3 switch (day) { case 1: println("Monday") break case 2: println("Tuesday") break case 3: println("Wednesday") break default: println("Invalid day") }
  1. For Loop: The for loop is used to execute a block of code a specified number of times.

Example:

css
Copy code
for (int i = 0; i < 5; i++) { println(i) }
  1. While Loop: The while loop is used to execute a block of code as long as a specified condition is true.

Example:

scss
Copy code
def count = 0 while (count < 5) { println(count) count++ }
  1. 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:

java
Copy code
def 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


  • captcha text