Thursday, November 19, 2009

15. Recursive programming in Free Pascal

Recursion is the process of working on a procedure repeatedly until we reach a solution. For example if you want to find out the sum of numbers starting from 1 increasing by 1 until 6, we start with 1 and make it as temporary sum and add to it 2,3 etc until we reach 6. The sum now gives the value we want.
We can also get the sum doing reverse computation. We start with 6(n) as the temporary sum and add to it 5(n-1) , decreasing 6 by 1.
Thus sum of 1 thru 6 is: sum(6) := 6 + sum 1 thru 5.
We keep on doing this repeatedly (recursive) until we reach 1, where we know the answer, the sum of a series of numbers starting with 1 and ends in 1, is 1.
if n =1 then sum := 1
Once we reach sum(1) = 1, we go back and solve all the equations and find the value of sum(6).

sum := n + sum(n-1);
sum(6) := 6 + sum(5),
sum(5) := 5 + sum(4) ,
sum(4) := 4 + sum(3),
sum(3) := 3 + sum(2),
sum(2) := 1 + sum(1),
sum(1) := 0 + 1 ** We know the answer for sum(1) and go backwards and solve the problem.

The main points in recursive programming is: Doing repeatedly the same process until we reach a condition to break the repetition. The condition is important because, if it is not there we will be repeatedly calling the process until we fill up the memory and crash.

Program15 Illustrates Recursive programming with two recursive functions sum and fact.

if n = 1 then sum := 1 else sum := n + sum(n-1);

if n = 0 then fact := 1 else fact := n * fact(n-1);

Program 15 follows:

Program program15;
{Author: Rao S Lakkaraju}
{Recursive Programming}
uses crt;

var n,m : integer;

function sum (n:integer) :integer;
begin
writeln('n is ',n);
if n = 1 then sum := 1 else sum := n + sum(n-1);
Writeln('sum is ',sum);
end;

function fact(n:integer) : integer;
begin
if n = 0 then fact := 1 else
fact := n * fact(n-1);
end;

begin
clrscr;
write('Please enter an integer to sum to ');
readln(n);
m := sum(n);
writeln('Sum of 1 to ',n,' is ',m);

write('Please enter an integer for factorial ');
readln(n);
m := fact(n);
writeln('Factorial of ',n,' is ',m);
Writeln( '**** My fifteenth Pascal Program ****');
readln;
end.

SUMMARY: Recursive programming is calling a known process repeatedly until we reach an end condition. We should know the process and the end condition where that process stops, otherwise we end up nowhere like driving a car without knowing where to stop.

No comments:

Post a Comment