August 1997
CA208: 'C' PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

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

5. (a) Write a self-contained C program that prints the square of the integers 0 through 9:
Print the square of the integers 0 through 9:
(i) using a for statement [3]
For-loop:
[3 marks]
(ii) while statement [3]
While-loop:
[3 marks]
Use the following marking scheme for both programs:
one mark for starting the loop at zero.
one mark for stopping after printing 92
one mark for the printf of i*i
(b) Given the following definition of a linear linked-list type as the representation of the elements in a stack,

(i) Write a procedure push, that has the procedure prototype shown below, that pushes the the element x onto the stack stack. [4]
void push(StackType *stack, int x);
A definition of push follows:
and the following marking scheme should be used:
one mark for creating a fresh StackElement.
one mark for assigning data into the stack element.
one mark for making the next field what is currently at the top of the stack.
one mark for changing the top of stack to the new node.
no marks should be deducted for trivial syntactic errors.
[4 marks]
(ii) Write a function sizeStack, that has the function prototype shown below, that returns the number of elements in the stack stack. [4]
int sizeStack(StackType stack);
A definition of sizeStack follows:
and the following marking scheme should be used:
one mark for creating two temporary variables and assigning them to zero and the top of stack.
one mark for iterating down the stack until a NULL is reached.
one mark for incrementing the size counter.
one mark for moving the temporary stack element pointer onwards.
no mark should be deducted for trivial syntactic errors.
[4 marks]
(iii) Write a function pop, that has the function prototype shown below, that returns and then removes the top element from the stack stack. You should call the function error (with prototype below), if it is not possible to remove an element from the stack. [6]
int pop(StackType *stack);
void error(void);
A definition of pop follows:
and the following marking scheme should be used:
two marks for raising an error when the stack is empty
one mark returning the data held at the top of stack.
two marks changing the top of stack pointer to point to the second element in the stack.
one mark for freeing the node at the top of stack.
no marks should be deducted for trivial syntactic errors.
[6 marks]