Labs and Tasks: Recursion
The recurrent formula
ExampleTo do: Calculate an addition of the sequence from 1 to n (n is entered).
expected output:
N=51+2+3+4+5=15result:
function sum(n: integer): integer; begin if n=1 then result:=1; if n>1 then result:=n+sum(n-1); end; begin var n:=readinteger('input n to make a sequence [1..n]'); print(sum(n)) end.Example
To do:
Output the binary code of the numberresult:

Example
To do: Calculating the sum of the digits of a number
- The recurrent formula (ratio) determines the value of the current member of the sequence through one or more preceding ones.
- One or more initial members of the sequence must be defined.
Recursion – pros and cons
with each new call, stack memory is consumed (stack overflow is possible), the cost of performing service operations during a recursive call{0.5}
Task 1:
To do: Write a recursive real-valued function Fact(N) that returns the value of N-factorial: N! = 1·2·…·N, where N (> 0) is an integer parameter. Using this function, output factorials of five given integers.
Expected output:
Please enter the distance in centimeters >>> 245 The distance in meters is 2
[Program name: Recur1.pas]
{0.5}
Task 2:
To do: Recur2. Write a recursive real-valued function Fact2(N) that returns the value of double factorial of N: N!! = N·(N−2)·(N−4)·…, where N (> 0) is an integer parameter; the last factor of the product equals 2 if N is an even number, and 1 otherwise. Using this function, output double factorials of five given integers.
Please enter the distance in centimeters >>> 245 The distance in meters is 2
[Program name: Recur2.pas]