Recursion
The main purpose of recursion in this context is to replace nested loop
structures of the following form:
Program loops;
const
zoveel = 4;
fac = 5;
var
k1, k2, k3, k4 : byte;
begin
for k1 := 1 to fac do
for k2 := 1 to fac do
for k3 := 1 to fac do
for k4 := 1 to fac do
begin
Writeln(k1,' ',k2,' ',k3,' ',k4);
end;
end.
The problem is that one cannot dynamically change the depth of the loop
structure here, that is the number of loop indices k1, k2, ... kN. This is the
real reason why recursion comes in. Just change the constant zoveel
(make it 2, 3 or whatever) in the following program and you're done!
Program recursie;
const
zoveel = 4;
fac = 5;
var
loper : array[1..zoveel] of byte;
procedure loops(diep : byte);
var
d : byte;
begin
if diep = zoveel then
begin
for d := 1 to zoveel do
Write(loper[d],' ');
Writeln;
end else begin
for d := 1 to fac do
begin
loper[diep+1] := d;
loops(diep+1);
end;
end;
end;
begin
loops(0);
end.
This is not to say, however, that recursion is necessary here (and/or
elsewhere).
I still have to see any example where the effect of recursion
cannot be accomplished by other means:
Program omzeild;
const
zoveel = 4;
fac = 5;
var
k, loper : byte;
totaal, L, macht : Longint;
begin
totaal := 1;
for k := 1 to zoveel do
totaal := totaal * fac ;
for L := 1 to totaal do
begin
macht := totaal;
for k := 1 to zoveel do
begin
macht := macht div fac;
loper := (((L-1) div macht) mod fac) + 1;
Write(loper,' ');
end;
Writeln;
end;
end.