Groovy 12 – Loops

There are 3 types  of loops:

while loop
do-while
for loop

while Loop

while(condition){  
//execute some code  
}  

As long as the condition is true the code encapsulated in between brackets will keep executing

Example:

while(var_x<=10){  
println(var_x)  
var_x++  
}  

 

Output is:

0

1

2

3

4

5

6

7

8

9

10

do – while loop

do{  
//execute some code  
}while(condition)  

 

The code in between brackets will execute at least one time and keep executing as long as the condition is true

  int var_x = 80;  
  do{  
  println(var_x);  
  var_x++;  
  }while(var_x<= 10); 

 

Output of this is:

80

 

for loop

for(initialization; condition; increment){  
   //execute some code  

 

First we start from  a value, that is the initialization, then a condition is placed, so code executes as long as the condition is true, then that value gets incremented.

Example:

for(int i = 0 ; i <=10; i++){  
println(i)  
}  

 

Output is:

0

1

2

3

4

5

6

7

8

9

10

When to use them.

Use while loop when you don’t know exactly how long you want some code to keep executing.

Use do-while, when you want your code to execute at least one time, regardless if the condition you place is true or false.So do-while is used when you want some code to be executed at least 1 time.

Use for loop when you know precisely how long you want to execute some code and from where to start.

Special case of for loop: for – each

for(vaiable : collection){  
//code to execute  

 

– is used to make your code compact

– helps when you need to cycle through a collection of data

– also helps in reducing risk of programming errors

Example

int var_array = {1,2,3,4}  
for(int i: var_array){  
println(i)  

 

The output  of this code in run-time messages will be :

1

2

3

4

Infinite loop

An infinite loop is a cycle that never ends, so the environment will give you an error like

oracle.jbo.ExprTimeoutException Expression timed out.

Example of infinite loop:

def var_x = 80  
while(var_x)  
{  
println(var_x)  
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *