August 2000
CA208 : 'C' PROGRAMMING

QUESTION 5

Total Marks: 15 Marks

Click here to access other questions

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

(a) Give an example of a program control flow statement in C. [1 mark]
(a) Any example such as a for loop, while, etc. [1 mark]

(b) Explain what is meant by the base case of a recursive test, and explain why it is necessary for a recursive test to have a base case. [2 marks]
(b) • The base case is the test which tells the function whether to continue recursing or not; (1 mark)
• Without one the function may go into an infinite recursion; (1 mark)
[2 marks]

(c) Explain the difference between stack and heap allocated data in C. [2 marks]
(c) • Heap allocated data is allocated by the programmer; (1 mark)
• Stack allocated data is created by the program for local variables and parameters; (1 mark)
[2 marks]

(d) The following function is intended to swap the integers a and b. Identify the problem with this function, and show how this could be remedied.
void Swap(int a, intb) {
  int temp= b;
  b= a;
  a= temp;
}
[2 marks]
(d) • The parameters are passed by value; (1 mark)
• it should be references which are passed in; (1 mark)

(e) Write a function that prompts the user to enter a number in the range 0 - 5. If the number is not in that range, the prompt should be repeated, else the function should return the number input. [4 marks]
(e) A sample definition follows:
int MyFunction() {
  int i= -1;
  while(i<0 || i> 5) {
    printf("enter a digit in hte range 0-4:");
    scanf("%d" &i);
  }
  return i;
}
And the following marking scheme should be used:
• Declaring a loop which runs until a number in the correct range is entered; (1 mark)
• A suitable printf; (1 mark)
• Reading in the integer into the reference; (1 mark)
• Returning the value when appropriate; (1 mark)
[4 marks]

(f) Implement the recursive procedure Remainder, such that it takes three parameters, a number, a divisor and a remainder. The function should recursively subtract the divisor from the number until only the remainder remains; and return the remainder to the caller. [4 marks]
(f) A sample definition of Remainder follows:
void Remainder(int n, int d, int* r) {
  if(n > d)
  Remainder(n-d, d, *r);
  else
  *r= d;
}
And the following marking scheme should be used:
• Correctly identifying the value and reference parameters; (1 mark)
• Testing for the base case where the division is complete; (1 mark)
• Performing the recursive call with the new parameters when it has not been reached; (1 mark)
• Setting the remainder when it has; (1 mark)
[4 marks]