Loops
The three main loops in free pascal , aka the programming language used in simba are:
- For do loop
- Repeat until loop
- While do loop
A loop statement allows us to run a bit of code multiple times.
1: For Do Loops
program new;
procedure ForDoLoop;
var
i: integer;
begin
for i:= 1 to 5 do
begin
writeln('Hi this is the for do loop');
writeln('This is loop number ',i)
end;
end;
begin
ForDoLoop;
end.
In the above example we create a simple procedure called ForDoLoop, and with in that procedure we specify the var i as an integer.
To use a for do loop, you must specify a integer for the loop to increment.
Then to get the loop started we say for i equals 1 to 5 do write the lines 'Hi this is the for to do loop' and 'This is loop number' , i.
The last thing to do is, call that procedure down in the main loop. Now if we run this bit of code.
Results:
Notable features of this loop:
- Make code look nicer, as you dont have to inc the integer.
- Less lines of code then the others.
2: Repeat Until
program new;
procedure RepeatUntilLoop;
var
i: integer;
begin
repeat
inc(i);
writeln('Hi this is a loop');
writeln('This is loop number ',i);
until(i = 8)
end;
begin
RepeatUntilLoop;
end.
In the above example we create a simple procedure called RepeatUntilLoop, and with in that procedure we specify the var i as an integer.
Then we say repeat: increment i and write the lines 'Hi this is the for to do loop' and 'This is loop number' i , until i is equal eight.
The last thing to do is, call that procedure down in the main loop. Now if we run this bit of code.
Results:
Notable features of this loop:
- Will repeat until the boolean given is true, AkA when i is equeal to eight.
- No need for begin and end on multiple lines of code. As repeat is like begin and until is like the end.
3: While Do Loops
program new;
procedure WhileDoLoop;
var
i: integer;
begin
while i < 5 do
begin
inc(i);
writeln('Hi this is a loop');
writeln('This is loop number ',i);
end;
end;
begin
WhileDoLoop;
end.
In the above example we create a simple procedure called WhileDoLoop, and with in that procedure we specify the var i as an integer.
Then we say while i is less than 5 do increment i and write the lines 'Hi this is the for to do loop' and 'This is loop number' i
The last thing to do is, call that procedure down in the main loop. Now if we run this bit of code.
Results:
Notable features of this loop:
- The loop continues to execute until the Boolean expression becomes FALSE, AKA when i isn't less then five.
P.S I forget to change the write line text but you guys get the idea.