August
1999 QUESTION 4 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
(a) | (i) Explain what is meant by a recursive
function. (ii) Explain what is meant by the base case of a recursive function. |
[2] [2] |
(i) A recursive function is
(ii) The base case of a recursive function
|
||
(b) | Using a while loop, write a function sum, which takes two parameters. The first parameter is a pointer to an array of integers, and the second is the length of the array. The function should return the result of summing every element in the array. Both of the parameters should remain unchanged. | [4] |
A sample definition of sum follows: int sum(int* a,
int b)
|
||
(c) | In mathematics, N! (known as N factorial)
can be computed using the formula N! = N * ( ( N - 1 ) ! ) The base case, 0!, is defined as being 1. Write a recursive function, called Factorial, which takes a single reference parameter, integer N, and returns the integer N!. On exiting, the parameter should remain unchanged. |
[4] |
A sample definition of Factorial as follows: int
Factorial(int* n)
|
||
(d) | Using a for loop, write an iterative function, Power, which takes two reference integer arguments, mantissa and exponent, and returns of raising the mantissa to the power exponent. You can assume that both parameters supplied to the function initially will be positive (non zero) integers. | [4] |
A sample definition of
Power follows: int
Power(int* mantissa, int* exponent) total=*mantissa;
|
||
(e) | Write a function CallPower, which takes two
integer parameters, x and y. Using a for loop and your Power function, the function should
print out the values of xy for all values from 0 up to x. For example, a call
to CallPower(4, 3) would produce the following output: 0 ^ 3 = 0 |
[4] |
A sample definition of CallPower follows: void
CallPower(int x, int y) {
|