Loops¶
What are the loops in Free Pascal?¶
- For Loop.
Remarks
- Free Pascal calculates the upper bound once before setting the counter variable.
- You can't change the value of a loop variable inside the loop.
- The loop variable's value is unclear after the loop ends or if the loop doesn't run. If the loop stops early due to an exception, break, or goto statement, the variable keeps its last value.
- If you're using nested procedures, the loop variable must be a local variable. Using a loop variable outside the nested procedure will cause a compiler error, but using a global variable is allowed.
Adapted from https://www.freepascal.org/docs-html/ref/refsu58.html#x168-19200013.2.4
- For-In Loop.
- While Loop.
- Repeat Until Loop.
- Nested Loops.
// Basically, a loop inside another loop
// A simple example (among many others)
for counter_a := initial_value_a to final_value_a do
for counter_b := initial_value_b to final_value_b do
begin
// code to run
end;
Examples¶
The snippet below demonstrates different types of loops in Free Pascal.
If you run the program, the output would be as follows (with b
to answer the question in the Repeat Until loop).
What are best use cases for each loop?¶
For Loop¶
Best for:
- Iterating a block of code over a fixed number of times.
- Keeping track of loop counter.
For examples:
- Reading and processing all elements in a fixed-size array.
- Copying N files from one location to another.
For-In Loop¶
Best for:
- Looping through collections, arrays, or enumerable types without manual indexing.
- Iterating tasks without a loop counter.
Examples:
- Printing all names in a list of people.
- Checking if an object exists in an collection.
While Loop¶
Best for:
- Repeating a block of code as long as a condition remains true, without knowing the exact number of repetitions in advance.
Examples:
- Reading user input until they enter a specific value.
- Reading command line options until no more options are found.
Repeat Until Loop¶
Best for:
- Like While Loop, but ensuring execution of a block of code at least once, even if the initial condition is false.
Examples:
- A login system that repeatedly requests credentials until authentication is successful.
- Reading a CSV file while ensuring that specific columns are present before processing its contents.
Nested Loops¶
Best for:
- Working with N-dimensional arrays or collections.
- Generating patterns based on multiple arrays.
Examples:
- Populating a 3x3 array of integer.
- Finding possible combination of words between N array of strings.