1. Simple Repetition Loop (LOOP)
The simplest form of loop, LOOP enables repeating a section of code a predetermined number of times.
Structure:
loop NumberOfRepetitions do
BlockOfCommands;
Key Points:
- Fixed number of iterations.
- Ideal for quick, concise tasks involving a known amount of repetitions.
Example 1:
begin
loop 3 do
print('Good morning!');
end.
Example 2:
begin
var sum := 0;
var i := 1;
loop 5 do
begin sum += i;
i++;
end;
print('Sum of first five numbers:', sum);
end.
2. Count-controlled Loop (FOR)
The FOR loop operates by systematically increasing or decreasing a counter variable across a specified interval.
Structure:
for CounterVariable := StartValue to EndValue do
BlockOfCommands;
Key Points:
- Ideal for processing sequences or collections (like arrays).
- Flexible movement possible either forwards (to) or backwards (downto).
Example 1:
begin
for var i := 2 to 10 do
if i mod 2 = 0 then
print(i);
end.
Example 2:
begin
var result := 1;
for var i := 1 to 5 do
result *= i;
print('Factorial of 5:', result);
end.
3. Pre-test Loop (WHILE)
The WHILE loop performs a sequence of actions repeatedly as long as a specified condition holds true.
Structure:
while ConditionIsTrue do
BlockOfCommands;
Key Points:
- Executes only if the initial condition is satisfied.
- Carefully manage the termination criterion to avoid infinite loops.
Example 1:
begin
var num : real;
print('Enter a positive number:');
readln(num);
while num <= 0 do
begin
println('Incorrect! Enter a positive number:');
readln(num);
end;
println('Thank you for entering a valid number.');
end.
Example 2:
begin
var sum := 0;
var i := 1; while i <= 10 do
begin
sum += Round(1/Sqr(i)); i++;
end;
print('Result of series calculation:', sum);
end.
4. Post-test Loop (REPEAT...UNTIL)
The REPEAT loop guarantees at least one execution of the code block before evaluating the exit condition.
Structure:
repeat
BlockOfCommands;until ExitConditionMet;
Key Points:
- Ensures the code segment runs at least once.
- Excellent for scenarios requiring immediate action regardless of initial circumstances.
Example 1:
begin
const ValidPassword = 'securecode';
var attempt : string;
repeat
print('Enter your password:');
readln(attempt);
until attempt = ValidPassword;
println('Access granted!');end.
Example 2:
begin
println('Provide two integers:');
var a, b : integer;
readln(a, b);
repeat
if a > b then
a -= b
else
b -= a;
until a = b;
println('Greatest Common Divisor:', a);
end.