When your program needs to repeat a sequence of instructions you will need to use a loop. There are three main types of loop in Delphi:
A while loop checks a condition at the start of each iteration, and executes the enclosed statements only if the condition is met:
For loops in Delphi are a little different to for loops in many other languages, but the basics are still the same. You will use a for loop to repeat the enclosed statements a set number of times, changing the value of a specified variable with each iteration.
In the example above, the value of i is initially set to 1, and the enclosed statements will be executed. On the second iteration the value of i is increased to 2, and the enclosed statements are executed. This will continue until the value of i exceeds 100.
Counting down in a for loop
By default, Delphi for loops will count upwards. If you need to count backwards in a Delphi for loop you will need to use the downto keyword:
Repeat Until Loops
Repeat until loops are a lot like while loops, but cruicially the condition is evaluated after the first iteration of the loop.
It is also important to note that the loop will stop running if the condition is met, where while loops stop when the condition is not met.
Delphi provides two additional statements you can use to add a bit more control to your loops.
To exit a loop, you can use the break statement:
To instantly jump to the next iteration of a loop, you can use the continue statement:
An infinite loop is a common programming mistake where a program will enter a loop that will never exit, consider the following:
In the example above, the value of i is set to zero. We then enter a while loop which will test the value of i is less than 100. As none of the statements inside the loop will change the value of i, the value of i will always be less than 100, and the loop will never terminate.