Download presentation
Presentation is loading. Please wait.
1
Advanced Higher Computing Science
Recursion
2
In this session we will look at the difference between iterative and recursive solutions to programming problems and what characterizes a recursive solution
3
Learning content What is recursion? Recursion pros and cons
Comparing iterative versus recursive solutions The stopping condition in recursion Recursive binary search Recursive quick sort Fractal graphics Recursion in Prolog Project: Must include a minimum of two from: standard algorithms (binary search, sorts, recursion) data structures (linked list, queues, stacks) data processing (SQL) web development (HTML forms, scripting)
4
Definition of recursion
Recursion: See Recursion A common "joke" in computing textbook indexes.
5
are where a procedure or function calls itself
Recursive programs: are where a procedure or function calls itself always need a "base case" or stopping condition A more helpful definition
6
Recursion pros and cons
Recursion is a powerful programming technique, and is efficient in that it often reduces the amount of code required Recursive code can be very memory intensive because sub procedure calls are all held in memory until the base condition is met Recursion can lead to an infinite loop if not terminated correctly Powerful but also dangerous
7
Descending Stars (iterative)
PROCEDURE descendingStars (INTEGER value) FOR outer FROM value TO 1 STEP -1 DO FOR inner FROM 1 TO outer DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY END PROCEDURE Task from National 4 usually used to get people to think about nested loops. In this example the procedure has been called with the value 5 as its parameter
8
Descending Stars (recursive)
PROCEDURE recursiveStars (INTEGER value) DECLARE newValue INITIALLY 0 IF value > 0 THEN FOR counter FROM 1 TO value DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY SET newValue TO value – 1 recursiveStars (newValue) END IF END PROCEDURE This is the recursive version of the same program. Note that the inner loop is replaced by a recursive call recursiveStars (newValue) recursiveStars is called with the actual parameter newValue (might be better if I had used Set here rather than DECLARE Again in this instance the procedure has been called with the value 5 as its parameter
9
Descending Stars (recursive)
If the value is zero then stop Otherwise call the recursiveStars procedure with one less than value Note that the variable newValue is local to the stars procedure, so every time recursiveStars is called, it is called with newValue as an actual parameter.
10
Descending Stars (recursive)
PROCEDURE recursiveStars (INTEGER value) IF value > 0 THEN FOR counter FROM 1 TO value DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY DECLARE newValue INITIALLY value – 1 recursiveStars (newValue) END IF END PROCEDURE Stopping condition There will always be one or more base cases or stopping conditions in a recursive sub program
11
Sum of numbers from 1 to n FUNCTION sumNums (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN sumNums (number-1) + number END IF END FUNCTION
12
the sum of all numbers between 0 and 1 is 1
Sum of numbers from 1 to n the sum of all numbers between 0 and 1 is 1 the sum of all numbers between that number and 1, is that number plus the sum of all numbers between it and that number -1 The sumnums of n = n + sumnums of (n-1)
13
Sum of numbers from 1 to n FUNCTION sumNums (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN sumNums (number-1) + number END IF END FUNCTION Stopping condition
14
Factorial of n (n!) FUNCTION factorial (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN factorial (number-1) * number END IF END FUNCTION Factorial is a function important in probability calculations The number of possible permutations of n items is n! (gets very large very quickly)
15
The factorial of any number n is n times the factorial of (n-1)
Factorial of n (n!) The factorial of 1 is 1 The factorial of any number n is n times the factorial of (n-1)
16
Factorial of n (n!) FUNCTION factorial (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN factorial (number-1) * number END IF END FUNCTION Stopping condition
17
Recursive Binary search
IF <the middle item in the array = the search key> THEN <search key has been found> ELSE IF <middle item in the array < the search key> THEN <binarySearch the lower half of the array> IF <middle item in the array > the search key> THEN <binarySearch the upper half of the array> END IF When the binary search is considered as a recursive program, it looks a lot easier to understand.
18
Recursive Binary search
FUNCTION binarySearch (ARRAY OF INTEGER myArray, INTEGER left, INTEGER right, INTEGER valueToFind) RETURNS INTEGER DECLARE middle INITIALLY (left+right)/2 IF myArray[middle]= valueToFind THEN RETURN middle ELSE IF myArray[middle] < value THEN RETURN binarySearch(myArray, left, middle, valueToFind) RETURN binarySearch(myArray, middle+1, right, valueToFind) END IF END FUNCTION
19
Recursive Quicksort (ascending order)
PROCEDURE quickSort(ARRAY OF INTEGER list, INTEGER left, INTEGER right) DECLARE pivotPosition AS INTEGER INITIALLY 0 IF left < right THEN SET pivotPosition TO partition(list, left, right) quickSort(list, left, pivotPositon) quickSort(list, pivotPositon + 1, right) END IF END PROCEDURE FUNCTION partition (ARRAY OF INTEGER list, INTEGER left, INTEGER right) RETURNS INTEGER <swaps the items in the list and returns a new pivot position> END FUNCTION Another divide and conquer recursive algorithm
20
Fractal Graphics: the Koch snowflake
PROCEDURE side (REAL length, INTEGER iterations) IF (iterations = 0 THEN penMove (length) ELSE side (length, iterations -1) penRotate (-60) penRotate (120) side (length , iterations- 1 ) END IF END PROCEDURE Fractal graphics make a lot of use of recursion, because of course a fractal is just an infinitely repeated formula. Fractals frequently feature in nature, although randomness is also part of the equation. Coastlines can be considered to be one of natures fractals. Zoom in on any coastline and it will still look like a coastline until you get down to the molecular level. side (40, 1)
21
Fractal Graphics: the Koch snowflake
PROCEDURE recursiveSide (REAL length, INTEGER iterations) IF (iterations = 0) THEN penMove (length) ELSE recursiveSide (length, iterations -1) penRotate (-60) penRotate (120) recursiveSide (length, iterations- 1 ) END IF END PROCEDURE side, (10 3)
22
Fractal Graphics : the Koch snowflake
PROCEDURE kochFractal (REAL length, INTEGER iterations) penDown() penHome() FOR counter FROM 1 TO 3 DO penRotate (120) recursiveSide(length,iterations) END FOR END PROCEDURE kochFractal (10, 3)
23
Integer to Binary string
FUNCTION binaryString (INTEGER number) RETURNS STRING DECLARE newDigit INITIALLY 0 DECLARE smallerNumber INITIALLY 0 DECLARE newString INITIALLY "" IF number = 1 THEN RETURN "1" ELSE SET newDigit TO asciiValue (number MOD 2) SET smallerNumber TO number \ 2 #integer division SET newString TO binaryString (smallerNumber) RETURN newString & newDigit END IF END FUNCTION FUNCTION asciiValue (INTEGER number) RETURNS STRING <convert single digit to ASCII value of number to newString > RETURN newString This is an example in the Scholar notes. The asciValue function will often be a standard one which comes with the programming language. CHR$ in basic, CHR in Python
24
Prolog: Programming in Logic
Prolog is a declarative language Prolog programs often make use of recursive techniques. Prolog programs consist of a set of facts and rules. These facts and rules together make up the knowledge base. When a program is run, the compiler (often referred to as the inference engine) will match the inputs to the program with these facts and rules to work out their logical consequence. If you did the AI topic in the old Higher then you will be familiar with prolog
25
Prolog: Sum of numbers sumnums(1,1). sumnums(Number,Sum):- Newnumber is Number - 1, sumnums(Newnumber, Smallersum), Sum is Smallernumber + Number. Fact: The sumnums of 1 is 1 Rule: The sumnums of any other number is that number plus the sumnums of one less than that number
26
Prolog: Factorial factorial(1,1). factorial(Num,Answer):- Nextnum is Num - 1, factorial(Nextnum,Nearly_answer), Answer is Num * Nearly_answer. Fact: The factorial of 1 is 1 Rule: The factorial of any other number is that number times the factorial of one less than that number
27
Prolog: Total of a list total([],0). total([Head|Tail],Answer):- total(Tail,Tail_total), Answer is Head + Tail_total. Fact: The total of an empty list is zero Rule: The total of any other list is the head plus the total of the tail
28
Prolog: member of a list
member_of(Item,[Item|Tail]). member_of(Item,[Head|Tail]):- member_of(Item,Tail). Fact: An item at the head of a list is in that list Rule: An item is in a list if it is in the tail of that list
29
Prolog: member of a list
Query Rule Fact ?- yes answer
30
Prolog: linear search (list)
pos_of_item(Item,[Item|Tail],1). pos_of_item(Item,[Head|Tail],Pos):- pos_of_item(Item,Tail,Newpos), Pos is Newpos + 1. In the case of the item not being present in the list the prolog inference engine would return "no" Fact: The item at the head of a list is in position 1 Rule: The position of any other item is one more than its position in the tail of the list
31
List Processing: descending values
A list record is defined recursively as a head (the first item in the list) , followed by the rest of the list (its tail). RECORD List IS {INTEGER head, List tail} FUNCTION integers (INTEGER n) RETURNS List IF n = 0 THEN RETURN {} ELSE RETURN {n, integers(n-1)} END IF END FUNCTION This recursive function will return an ordered list of integers from n down to 1. It uses the fact that a list with nothing in it is an empty list {}, and the rule that any other list will be made up of n followed by a tail which is a made up of a list of numbers from n-1 down. A list can be defined recursively as a record
32
List Processing: Insert a value
RECORD List IS {INTEGER head, List tail} FUNCTION insert (INTEGER n, List myList) RETURNS List IF myList = {} THEN RETURN {n,{}} END IF IF n > myList.head THEN RETURN {n, myList} ELSE RETURN {myList.head, insert (n, myList.tail)} END FUNCTION This recursive insert function inserts an integer n into a list newList. It uses the fact that inserting an integer into an empty list creates a new list made up of n followed by an empty list, and the fact that inserting an integer n which is greater than the head of the list creates a new list made up of n followed by that list. The rule is that inserting any other integer results in a new list consisting of the head of the list followed by the result of inserting n into the tail of the list.
33
List Processing: Insert a value
If the following code segment was executed, what would the contents of newsList1 and newList2 be? SET myList TO integers(4) SET newList1 TO insert (7, myList) SET newList2 TO insert (3, newList1) newList1 = {7,4,3,2,1} newList2 = {7,4,3,3, 2,1}
34
List processing: Linear search
RECORD List IS {INTEGER head, List tail} FUNCTION linearSearch (INTEGER target, List numbers) RETURNS INTEGER IF numbers = {} THEN RETURN -1 END IF IF target = numbers.head THEN RETURN 1 ELSE RETURN linearSearch (target, numbers.tail) + 1 END FUNCTION This algorithm is almost identical to the prolog program we saw earlier Fact: The empty list contains no items Fact: The item at the head of a list is in position 1 Rule: The position of any other item is one more than its position in the tail of the list
35
Summary Recursion is a powerful programming technique which often results in more elegant and readable code Many problems can be more easily solved using recursion rather than iteration Recursive code can be very memory intensive because sub procedure calls are all held in memory until the base condition is met
36
Thank you. Please take a minute to give your evaluation for today's session at
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.