August 1999
CA208 : 'C' PROGRAMMING

QUESTION 4

Total Marks: 20 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to
Question 4

(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
  • One which calls itself;
  • Until a terminating condition is reached.

(ii) The base case of a recursive function

  • Is the case which causes the function to stop recursing;
  • And climb back up the recursive stack.

 

(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)
{
   int count=0;
   do {
          count= count+ (*a);
          *a++;
           b--;
        } while (b!=0);
    return count;
}

 

(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)
{
   if( (*n) == 0 )  {
     return 1;
   }  else {
      return n * Factorial( (*n)-1 );
}
}

 

(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)
{
   int count, total;

   total=*mantissa;
   for(count=1; count<= *exponent; count++)
       total = total* *mantissa;
     return total;
}

 

(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
1 ^ 3 = 1
2 ^ 3 = 8
3 ^ 3 = 27
4 ^ 3 = 64

[4]
A sample definition of CallPower follows:

void CallPower(int x, int y)  {
int a;
   for(a=0; a<=x; a++)
   printf("%d ^ %d = %d\n", a, y, Power(&a, &y) );
}