Question 1 Report
A program is needed to reverse a string entered by the user. For example, the input "HELLO" should produce the output "OLLEH".
(a) Write pseudocode for a function called ReverseString that takes a string as a parameter and returns the reversed string. [4]
(b) Complete the trace table to show how your function processes the string "CODE". [3]
| Iteration | Index | Character taken | Reversed (so far) |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
(c) State what would happen if an empty string "" is passed to your function. [1]
(a) The function builds a new string by reading characters from the original in reverse order, starting from the last character and working back to the first:
FUNCTION ReverseString(Original : STRING) RETURNS STRING
DECLARE Reversed : STRING
DECLARE i : INTEGER
Reversed <- ""
FOR i <- LENGTH(Original) TO 1 STEP -1
Reversed <- Reversed & Original[i]
NEXT i
RETURN Reversed
ENDFUNCTIONThe function header declares the parameter and return type [1]. The loop counts from LENGTH down to 1 [1]. Each character is appended (concatenated) to the growing Reversed string [1]. The completed string is returned [1]. [4]
(b) Processing the string "CODE" (length 4), the loop runs from index 4 down to 1:
| Iteration | Index | Character taken | Reversed (so far) |
|---|---|---|---|
| 1 | 4 | E | "E" |
| 2 | 3 | D | "ED" |
| 3 | 2 | O | "EDO" |
| 4 | 1 | C | "EDOC" |
The function returns "EDOC". [3]
(c) If an empty string "" is passed, LENGTH returns 0. The FOR loop condition (0 TO 1 STEP -1) is never satisfied because the start value is already less than the end value for a descending loop. The loop body never executes, and the function returns the empty string "". [1]
Everything you need to excel in your exams