Upper Six Computer Science
Monday 02 June 2025
Recursive Function to Iterative Function Translation
1. A program sorts an array of integers and searches the array for a particular value.
a. The array of integers, NumberArray, stores the following data in the order
given:
100 85 644 22 15 8 1
Write code to declare and initialise the array in the main program. [1]
b. The following recursive pseudocode function sorts the array into ascending
order using an insertion sort and return the sorted array.
DECLARE LastItem : INTEGER
DECLARE CheckItem : INTEGER
DECLARE LoopAgain : BOOLEAN
FUNCTION RecursiveInsertion(IntegerArray: ARRAY[] OF INTEGER,
NumberElements : INTEGER) RETURNS ARRAY[] OF INTEGER
IF NumberElements <= 1 THEN
RETURN IntegerArray
ELSE
CALL RecursiveInsertion(IntegerArray, NumberElements – 1)
LastItem IntegerArray[NumberElements -1]
CheckItem NumberElements – 2
ENDIF
LoopAgain TRUE
IF CheckItem < 0 THEN
LoopAgain FALSE
ENDIF
WHILE LoopAgain
IntegerArray[CheckItem + 1] IntegerArray[CheckItem]
CheckItem CheckItem -1
IF CheckItem < 0 THEN
LoopAgain FALSE
ELSE
IF IntegerArray[CheckItem] < LastItem THEN
LoopAgain FALSE
ENDIF
ENDWHILE
IntegerArray[CheckItem + 1] LastItem
RETURN IntegerArray
ENDFUNCTION
i. Write the program code for the pseudocode function RecursiveInsertion().
Copy and paste the program code. [4]
Page |1
ii. Write code to call the function, the array and the number of elements as parameters.
Output the word ‘Recursive’ and the content of the returned array. Copy and paste the
program code. [2]
iii. Test your program. Take a screenshot of the output(s). [1]
iv. Transform the function into an iterative function IterativeInsertion. [4]
v. Write code to call the iterative function, to perform the same function. Output the
word ‘Iterative’ and the content of the returned array. Copy and paste the program
code. [1]
vi. Test your program. Take a screenshot of the output(s). [1]
2. 01 def thisFunction(theArray, num1, num2, num3):
02 result = num1 + ((num2 - num1) % 2)
03 if num2 < num1:
04 return -1
05 else:
06 if theArray[result] < num3:
07 return thisFunction(theArray, result + 1, num2, num3)
08 elseif theArray[result] > num3:
09 return thisFunction(theArray, num1, result - 1, num3)
10 else:
11 return result
12 endif
13 endif
Rewrite the function thisFunction() so that it uses iteration instead of recursion.
Page |2