A loop is a control statement that allows us to repeat a code block. Loops contain a conditional which determines how many times the code block is repeated.
There are few different loop types:
For-loop
The for loop loops through a block of code a specified number of times.
for([variable declaration], [condition], [increment step]) {
[code block]
}
Code Block | ||
---|---|---|
| ||
for(intlet i=0; i <= 100; i++) { printlnprint(i); } |
For-In-loop
The for in loop loops through the properties of an object.
for([variable declaration], [condition], [increment step]) {
[code block]
}
Code Block | ||
---|---|---|
| ||
let person = {name:"Maik", surname:"Muster"};
let x;
for (x in person) {
print(x)
} |
While-loop
The while loop cycles through a block of code as long as its specified condition is true.
while ([condition]) {
[code block]
}
Code Block | ||
---|---|---|
| ||
intlet x=0; while(x <= 100) { printlnprint(x); x++; } |
Do-While-loop
do{
} while([condition]);
This is the same as the while loop, but we check the condition at the end of the code block. The do-while-loop will always execute at least once, no matter the condition.
...
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, it will then repeat the loop as long as the condition is true.
do{
} while([condition]);
Code Block | ||
---|---|---|
| ||
let x=0; do { printlnprint(x); x++; } while(x <= 100); |
Exercise
...
Write a program that creates a line of animated icons on the screen using a loop. Make use of the sin() function to create a simple oscillation.