April 1999
CA208: 'C' PROGRAMMING

QUESTION 2

Total Marks: 20 Marks

Click here to access other questions

Click to access
SAMPLE STUDENT'S SOLUTIONS
for Question 2

 

(a) (i) Define what is meant by a recursive function or procedure. [2]
(ii) Define what is meant by an iterative function or procedure.

 

[2]
(b) Assume the following output:

Downwards: 0 of 3
Downwards: 1 of 3
Downwards: 2 of 3
Downwards: 3 of 3
Upwards: 3 of 3
Upwards: 2 of 3
Upwards: 1 of 3
Upwards: 0 of 3

 

(i) Using while loops, write an iterative definition of the procedure levels, that takes two integer arguments, such that a call to levels(4, 3) produces nothing and a call to levels(0, 3) produces the output above. [4]
(ii) Write a recursive definition of the procedure levels, that takes two integer arguments, such that an initial call to levels(4, 3) produces nothing and a call to levels(0, 3) produces the output above.

 

[4]
(c) Assume the following function, which is intended to return a range of values depending on the contents of the string mystring:

int foobar(char* mystring) {
    switch(mystring) {
    case("hello"): return 1;
    case("world"): return 2;
    default: return 0;
    }
    return -1;
}

 

(i) Explain why this function is incorrect? [1]
(ii) Identify a construct which would be more suitable for achieving the desired functionality, and explain why this is the case.

 

[2]
(d) Given the following procedure:

void foobar(int state, int signal, int timeout) {
   switch (state) {
       case 1:
           if (signal) goto makerunnable;
           if (timeout > 0) {
               timeout = 0;
               printf("Wakeup task\n");
       makerunnable;
               printf("Restarting task\n");
               break;
           }

       default:
       printf("Delete task\n");

       case 2:
       printf("Running task\n");
   }
}

trace the following calls, and produce their output:

 

(i) foobar(2, 0, 0); [1]
(ii) foobar(1, 1, 0); [1]
(iii) foobar(1, 0, 10); [1]
(iv) foobar(3, 0, 10); [1]
(v) foobar(2, 1, 10); [1]