2. Recursion
All of the examples considered thus far
involved a main program referencing a
subprogram or one subprogram
referencing another.
A subprogram may also reference itself,
this is called Recursion.
3. Ex: n!
n! = 1 * 2* 3* … * n
0! = 1
1! = 1
2! = 1 * 2 = 2
3! = 2! * 3 = 2*3 = 6
4! = 3! * 4 = 6*4 = 24
It is clear that once one factorial has been
calculated, it can be used to calculate the
next one.
n! = n * (n-1)!
4.
A function is defined recursively if the
definition consists of two parts:
A base case: in which the value of the
function is specified for one or more values
of the argument(s) 0! = 1
A recursive step: in which the function’s
value for a current value of argument is
defined in terms of a previously defined
function value.
n>0 n! = n* (n-1)!
7. Notes
Subprograms may be declared to be
recursive by attaching the word
RECURSIVE at the beginning of the
subprogram heading.
For a recursive function, a RESULT
clause must be attached at the end of
the function heading.
8. Notes
Return value will be assigned to the
result variable instead of the function
name.
The type of the function is specified by
declaring the type of the result variable.
9.
Recursive function factorial(n) result(fact)
integer:: fact
integer,intent(in)::n
if(n==0) then
fact = 1
else
fact = factorial(n-1) * n
end if
End Function factorial
10.
Fact = 1
do I = 1,5
fact = fact * I
end do
Nonrecursive programs may execute more
rapidly and utilize less memory than
corresponding recursive programs.
For some problems, recursion is the most
natural and straightforward technique.
11. Ex:
Recursive function f(n) result(f_value)
integer:: f_value
integer,intent(in) :: N
if(n==0) then
f_value = 0
else
f_value = n+ f(n-1)
end if
end function f
!Find f(5), f(0)
12. Ex:
recursive function f(num1,num2) result(f_val)
integer:: f_value
integer,intent(in):: num1,num2
if (num1>num2) then
f_val = 0
Else if(num2==num1+1) then
f_val = 1
Else
f_val = f(num1+1,num2-1) + 2
End if
end function f !! F(2,2), F(1,5), F(8,3)
13. xn
Recursive function f(x,n) result(x2n)
integer:: x2n
integer,intent(in):: x,n
if(n==0)
x2n = 1
else
x2n = f(x,n-1) * x
end if
end function f