April 2000
CA208 : 'C' PROGRAMMING

QUESTION 4

Total Marks: 15 Marks

Click here to access other questions

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

Do not award half marks. Do not deduct marks for trivial syntactic errors. Alternative correct answers should be given credit, unless otherwise indicated in the marking scheme.

(a)(i)Explain the difference between pass by value and pass by reference [2marks]
•In pass by value changes made to the parameters by the procedure are not reflected in the parameters after the procedure has terminated.(1 mark)
•In pass by reference the changes made to the parameters are reflected in the calling code.(1 mark) [2 marks ]
(ii)Identify how pass by reference is implemented in C.[1 mark ]
In C, pass by reference is implemented using pointers.[1 mark ]

(b)Write a procedure,called reference which takes in two reference parameters x and y The procedure should change the two values such that on exit,x is equal to the sum of the two values,and y is equal to the difference between the two values.[3 marks ]
A sample definition of reference follows:
void reference(int* x, int* y) {
  int temp;
  temp= *x;
  *x= temp+ *y;
  *y= temp - *y;
}
And the following marking scheme shouldbe used:
•A suitable signature,with reference parameters;(1 mark)
•Correctly de-referencing pointers when performing arithmetic;(1 mark)
•A correct algorithm for calculating the sum and the difference.(1 mark)
[3 marks ]

(c)Using a switch statement,write a function,called itoa which takes a single integer parameter.If the parameter supplied is 1 then the function should return the character a if 2 then the character b should be returned; in all other cases the function should return the character c [4marks ]
A sample definition of itoa follows:
  char itoa(int i) {
  char rvalue;
  switch(i) {
  case 1:
    rvalue= ’a’;
    break;
  case 2:
    rvalue=’b’;
    break;
  default:
    rvalue= ’c’;
  }
  return rvalue;
}
And the following marking scheme shouldbe used:
•Correct use of switch statement basedon i;(1 mark)
•With correct use of break clauses; (1 mark)
•An appropriate default clause;(1 mark)
•Correctly returning characters.(1 mark)
[4 marks ]

(d)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. For example,3! =3 *2 *1 *1 =6. Write a recursive function,called factorial which takes as its parameter an integer n and will return N .[5 marks ]
A sample definition of factorial follows:
int factorial(int n) {
  if(n== 0)
    return 1;
  else
    return (n* factorial(n-1));
}
And the following marking scheme shouldbe used:
•A correct function signature;(1 mark)
•Testing the base case n== 0;(1 mark)
•Returning 1 in the base case;(1 mark)
•Recursing with n-1 when the base case has not been reached;(1 mark) •And returning n * the recursive call.(1 mark)