Thursday, July 21, 2011

Recursion in Delphi!

Recursion is a very generically used term in computer programming. Some problem in computer programming which allow repetition of some particular task again and again with some terminating check can be implemented very easily with the help of the concept of recursion.

A simplest example is to find the factorial of 5. The result is derived as -

5! = 5 X 4 X 3 X 2 X 1
5! = 120

This simple program can be easily designed using recursion or using recursive calls to the same function again and  again. e.g. -

fact() = fact(i) X fact(i - 1)

The above expression at each step calls the factorial function again with one value less for variable i in each call.

A simple Delphi program to demonstrate the recursion concept in Delphi is as follows -

A button click is used to trigger the recursive function -

procedure TForm1.Button1Click(Sender: TObject);
var
    a : integer;
begin
    a := fact(5);
    ShowMessage(inttostr(a));
end;

and the simple recursive function is -

function fact(i : integer) : integer;

begin
    if (i = 1) then
    begin
        fact := 1;
    end
    else
    begin
        fact := i * fact(i - 1);
    end;
end;
As we can see in the above example fact function calls itself till the value of i variable reaches 1 which is the terminating condition for our recursive function and no further recursions are made.

The result returned for above example is 120.

No comments: