> Tutorial
We are now going to look at another type of structure that is just as fundamental as conditions: loops!
A loop allows instructions to be repeated several times. There are several types that we will see in this part.
while loopThe while loop has a syntax similar to the if statement seen above. It allows an instruction block to be executed as long as a condition is met.
Here is an example:
This code will display in the logs when executed: > Counter is 1 Counter is 2 Counter is 3 Counter is 4 Counter is 5
do while loopThe do while loop is similar to the while loop, except that the condition occurs at the end, so the loop body is always executed at least once:
A possible display of the execution of the program: > x: 0.85712
for loopAnother slightly more complex type of loop exists, it looks like a while loop but more condensed. You will see in use that depending on the use case it is more practical to use a for or a while.
The for loop consists of three optional parts:
counter variable;counter variable.Example of a for loop:
This code will show in the logs: > Counter i is 1 Counter i is 2 Counter i is 3 Counter i is 4 Counter i is 5
Our leek has between 10 and 13 TP (thanks to Motivation) and the Pistol only costs 3 TP, so it can be used 4 times at most.
We use a for loop to execute the useWeapon function 4 times in a row:
Here our variable i will have the values 0, 1, 2 and 3 so the loop will do 4 iterations.
What is a loop for?
Executing statements multiple times Condense your code Speed up part of your code Execute instructions in parallel
Which code(s) are correct?
var x = 0 while (x var x = 0 for (var i = 0; i var x = 0 while { x += 2 } do (x var x = 0 for (; x
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.