August
1997 QUESTION 4 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
4. | (a) What are the values I and J in the following program segment? | [2] | ||
Values of I and J: | ||||
I = 6 | [1] | |||
J = 7 | [1] | |||
(b) What does the following program print? | [4] | |||
Award one mark for each of numbers in the output below. Do not deduct marks if the answers do not include the accompanying text such as val =.. one =... | ||||
val = 3 one = 2 | [2] | |||
val = 2 two =2 | [2] | |||
(c) Define implementations of the following library functions: | ||||
Implementation of strlen, strncpy, and strrev: | ||||
int strlen (char *str); | ||||
void strncpy (char *dst, char *src, int n); | ||||
void strrev (char *dst, char
*src); |
||||
(i) Where strlen, returns the number of characters in the string stc. | [4] | |||
Definition of strlen: | ||||
![]() |
||||
and the following marking scheme should be used: | ||||
one mark for iterating down the string str until a null character is found (may be a while or for-loop). | ||||
one mark for incrementing src so that the loop iterates down the string. | ||||
one mark for incrementing a temporary counter that holds the number of characters encountered during traversing the string. | ||||
one mark for returning the value of the temporary counter. | ||||
no marks should be deducted for trivial syntactic errors. | ||||
[4 marks] | ||||
(ii) Where strncpy, copies at most n characters of the string stc into dst. You can assume that dst is a character string with at least n elements. | [5] | |||
Definition of strncpy: | ||||
![]() |
||||
and the following marking scheme should be used: | ||||
defining an iteration statement (may be a while or for-loop), such that the loop is terminated when either a null character is seen, | [1] | |||
or n characters have been copied. | [1] | |||
During the i th iteration of the loop, the i th character from src needs to be copies into dst. | [1] | |||
During each iteration of the loop, n needs to be decremented. | [1] | |||
After the characters from src have been copied into dst, dst has to be null terminated. | [1] | |||
no marks should be deducted for trivial syntactic errors. | ||||
[5 marks] | ||||
(iii) Where strrev, copies a reversed version of src into dst. Note: you may use strlen in your definition. | [5] | |||
Definition of strrev: | ||||
![]() |
||||
and the following marking scheme should be used: | ||||
one mark for calculating len, the length of src | ||||
one mark defining an iteration statement (may be a for or while loop), that performs len iterations. | ||||
during iteration i, two marks should be awarded for assigning dst[i] = src[len - i-1]. Only one mark should be awarded if the assignment dst[i] = src[len - i] is used. | ||||
one mark for null terminating dst. | ||||
no marks should be deducted for trivial syntactic errors. | ||||
[5 marks] |