Come programmare in Grimport?

Chiedici aiuto con la programmazione in Grimport TRANSLATE THIS PAGE WITHOUT TOUCHING THE CODES

Control Structures

 

In this part, we will study control structures.

The control structures allow you to control the execution of the code. There are conditional structures and looping structures.

 

Conditional structures


Conditional structures will execute a certain number of instructions if and only if a certain condition is verified.

If statement

  • If

  • The if condition is one of the most used conditions and is also the simplest to understand since it will just allow you to execute a block of code if and only if the result of a test is true.

    First example:

    x = 3 
    if(x<1)
    { 
    	console("the value of x is less than 1") 
    } 
    if(x==1)
    { 
    	console("the value of x is equal to 1") 
    } 
    if(x>1)
    { 
    	console("the value of x is greater than 1") 
    }

    Output:

    // -> the value of x is greater than 1

    In the code above, the first two conditions are false while the third one is true.

     

    Second example:

    if(!test) 
    { 
    	//block of code to be executed 
    }

    In this example, if test = null, test = false, test = [], test = "" , then the block of code will execute.

     

  • If ... else

  • The if condition is limited because it only works when the result is evaluated to true. Whereas, the if...else structure is more complete and will allow us to execute the first block of code if the condition is true and a second block if the condition is false.

    Example:

    x = 0.5 
    if(x>1)
    { 
    	console("x is greater than 1") 
    } 
    else
    { 
    	console("x is less than or equal to 1") 
    }
    

    Output:

    // -> x is less than or equal to 1

    In the code above, the first condition is false.

    If our first condition had been true, the if would have been executed and the else would have been ignored.

     

  • If…else if…else

  • The if...else if...else condition is even more complete than the if...else condition because it will allow us to manage several cases.

    Example:

    x = 5 
    if(x<1)
    { 
    	console("the value of x is less than 1") 
    } 
    else if(x==1)
    { 
    	console("the value of x is equal to 1") 
    } 
    else
    { 
    	console("the value of x is greater than 1") 
    }

    Output:

    // -> the value of x is greater than 1

 

Compressed notation

It is possible to compress the above notation by putting the instructions after the statments or on the line below.
The example above becomes :

x = 5 
if(x<1) console("the value of x is less than 1") 
else if(x==1) 
  console("the value of x is equal to 1") 
else console("the value of x is greater than 1") 

 

Switch statement

The switch statement allows us to execute a code depending on the value of a variable. This statement is an alternative to if...else if...else.
However, these two instructions are not exactly the same because the switch will be bound to a specific case, without using superiority and inferiority operators.

A switch will have several possible cases, starting each of them with case.

Like the if, each case represents a block of code. The switch statement determines which block will be executed.

Example:

season = 3 
switch(season) 
{ 
	case 1: 
		console("Summer")
		break 
	case 2: 
		console("Automn") 
		break 
	case 3: 
		console("Winter") 
		break 
	case 4: 
		console("Spring") 
		break 
}

Output:

// -> Winter

You can notice that in a switch, you have to initialize the variable on which you are going to execute the switch (here we will initialize season = 3).
The value of the variable is equal to the value of a case. In the code above, we will execute case 3.

The keyword break forces an exit ofthe switch after executing the case. That means that it will end the execution of the switch immediately and continue the rest of the code after the closing bracket of the switch instruction. If you want to continue the switch instruction, just remove it.

When the value of the variable does not correspond to any case, we will have to use the default keyword which will have the same function as an else in an if...else.

Example:

season = 2 
switch (season) 
{ 
	case 1: 
		console("We are in Summer") 
		break 
	case 3: 
		console("We are in Winter") 
		break 
	default: 
		console("Looking forward to the Summer or Winter") 
}

Output:

// -> Looking forward to the Summer or Winter

Note that if the default statement is used as the last statement in a switch block, it does not need a break.

 

Looping structures


Looping structures will execute a block of code in a loop as long as a given condition is verified.

While loop

A while loop executes a set of instructions until a condition becomes false. This type of loop is used when the number of iterations is unknown.

Here is the general form of a while loop:

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

Example:
The loop code will be executed as long as the variable i is inferior to 5 :

i = 0
continue = true
while(continue) 
{ 
	console(i) 
	i++
    if(i >= 5) continue = false
} 

Output:

// -> 0 -> 1 -> 2 -> 3 -> 4

It is important to write i++ to increment the variable otherwise the loop will never end. Be careful with infinite loops that can crash a program.

For loop

When you know exactly how many times you want to execute a block of code, use the for loop instead of the while loop:

Here is the general form of a for loop:

for(statement 1, statement 2, statement 3) 
{ 
	// code block to be executed   
}

statement 1 is executed at the beginning of the loop and usually initiates a counter.
statement 2 is evaluated at each iteration, if statement 2 is true, the for iterations continue.
statement 3 is executed at the end of each iteration.

Example:
The code will display the odd numbers between 1 and 10:

for(i = 1; i < 10; i = i + 2) 
{ 
	console(i) 
} 

Output:

// -> 1 -> 3 -> 5 -> 7 -> 9

The instruction 1 (i = 1) defines a variable before the beginning of the loop.

The instruction 2 (i < 10) is the condition for the loop to execute. If the condition is true, the loop starts again, if it is false, the loop ends.

The instruction 3 (i+2) increases the variable each time the loop's block of code has been executed.

For-in loop

The for-in statement is used to iterate through a set of values.

Here is the general form of a for-in loop:

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

Example:
The code will display the name of employees:

employees = ["Ken",  "John", "Sally"] 

for(employee in employees)
	console(employee) 
    
// -> Ken -> John -> Sally  

With associative arrays, you can reference keys and values with .key and .value pointers.

Example:
The code will display the name and age of the 3 people with a sentence:

employees = ["Ken" : 21,  "John" : 25, "Sally" : 22] 

for(employee in employees)
{ 
	console(employee.key  + " is "+ employee.value + " years old") 
	console(employee) 
} 

Output:

//->  Ken is 21 years old 
//->  Ken=21 
//->  John is 25 years old 
//->  John=25 
//->  Sally is 22 years old 
//->  Sally=22 

 

 

Methods for iterating


There are two methods to iterate a list: each() and eachWithIndex().
These methods are used to iterate the object and return the value of the given object.

The each Method

The each() method accepts a closure and is very similar to the foreach() method in Java.

Example:

def days = ["Monday", "Tuesday", "Wenesday", "Thursday", "Friday"] 
days.each 
{
	console it 
} 

Output:

// -> Monday -> Tuesday -> Wenesdat -> Thursday -> Friday

The each method has a default iterator (it).

Instead of the it you can also name the element you want to iterate. This makes your code more readable.

Example:

def days = ["Monday", "Tuesday", "Wenesday", "Thursday", "Friday"] 
days.each 
{ day ->
	console(day) 
} 

You can also iterate maps.

Example:

map = [1: "a",  2: "b", 3: "c"] 
map.each
{ myKey, myValue-> 
	console(myKey + "=>"  + myValue) 
} 

Output:

// -> 1=>a -> 2=>b -> 3=>c

The eachWithIndex Method

Sometimes we want to know the index during the iteration. In this case we use the eachWithIndex() method.

It is more complete than the each() because eachWithIndex() provides the value of the current index in addition to the current element.

Example:

day = ["Monday", "Tuesday", "Wenesday", "Thursday", "Friday"] 
day.eachWithIndex
{ day, index-> 
	console ("We are " + day + " and it's day number " +(index+1)

) }

Output:

// -> We are Monday and it's day number 1 -> We are Tuesday and it's day number 2 -> ...

The eachWithIndex method has a default index (index) which you can name whatever you wish to.

 

The break and continue statements


The break statement

We have seen in the case of the switch the break statement, which allows you to leave, under certain conditions, a structure. We can also find the break statement in other structures.

Example:
This code allows you to go through all the values between 0 and 10 with a for loop, except in the case where you find the value 6 then you stop the execution of the loop:

for(i=0; i<=10; i++ ) 
{ 
	if ( i == 6 ) break 
	console( "i = " + i ) 
}

Output:

// -> i = 0 -> i =1 -> i = 2 -> i =3 -> i = 4 -> i = 5

The continue statement

Unlike the break statement, continue is a statement that allows you to skip a turn in the execution of a loop.

Example:
This code calculates the sum of the first ten positive integers, except for the value 6:

int sum = 0

for(i=1; i<=10; i++ ) { if ( i == 6 ) continue sum += i } message = "The sum of the first ten positive integers (private of 6) is : " console( message + sum)

Output:

// -> The sum of the first ten positive integers (private of 6) is : 49

 

 


Next ❯ ❮ Previous