Programming Logic/Looping

From Wikiversity
Jump to navigation Jump to search

Looping is when a certain order of commands are repeated (endlessly or a certain number of times or until something else happens)


Endless loops[edit]

For this case, the code is executed forever. This is dangerous. This can happen if a counter variable is not incremented, or if the condition is always true and the loop will therefore never stop.

Example:

{
Step forward
Repeat
}

The roboter would endlessly walk forward



Loops repeated a certain number of times[edit]

For this case, some kind of counter is used to keep track of how many iterations of the loop have been executed.

Example:

{
step forward 
repeat 10 times
}

The roboter would take 10 steps and then stop.


Conditional loops[edit]

In this case, the code is executed and operations performed either while a certain condition is true, or until a certain condition becomes true.

Example:

{
step forward
repeat until you are in front of wall
}

In this case the roboter would walk forward until it is in front of a wall. It would not matter how far away it is (that means you don't have to re-program the robot when you have another distance). Then it would continue the program.