Loops
It is used in repetitive operations. There are 3 types of loops. What is written in first parenthesis after "loop" determines type of loop. First code after parenthesis or curly brace will run until loop ends or is broken.
Conditional Loop:
It was running 1 time if condition in "if" statement gave value "true". In "loop" expression, if it returns "true", loop will run until it returns "false" or loop is broken.
Usage: loop(condition) code;
Example:
Int num=0;
loop(num<20){
num+=5;
print(num);
}
/*
Output:
5
10
15
20
*/
If first parenthesis after "loop" is left blank, it will default to "true". So an infinite loop occurs. Program can be terminated with Control-C.
Example:
loop() print("A"," "t);
//It will print "A" forever.
//Output: A A A A A A A A A ...
Repeat Loop:
It is used to run code a certain number of times.
Usage: loop(start; condition; update) code;
"start" part runs 1 time. In "condition" section, condition of loop is written. "update" section runs after every code or curly braces run.
Example:
//Let's create an integer "n" and set its value to "0".
//Let's say that the loop will run as long as the integer "n" is less than "5".
//Let's increase the integer "n" by 1 after each code or curly braces work.
loop(Int n=0; n<5; n++) print(n);
/*
Output:
0
1
2
3
4
*/
Travel Loop
It is used to navigate elements of Arrays and Lists.
Usage: loop(DataType variable:list){<codes>}
Example:
Text[] products=new Text[]{"apple", "pear", "banana"};
loop(Text product:products) print(product);
/*
Output:
apple
pear
banana
*/
Break Loop
"break;" when trying to terminate loop code is used.
Example:
loop(Int n=0; n<5; n++){
print(n);
if(n==1) break;
}
/*
Output:
0
1
*/