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 fu...

Assessment: Computer Science (9-1) 0984 | Paper 2 Mock 01 | Algorithms, Programming and Logic Subject: Computer Science (9-1) - 0984

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]

IterationIndexCharacter takenReversed (so far)
1
2
3
4

(c) State what would happen if an empty string "" is passed to your function. [1]

Answer Details

(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
ENDFUNCTION

The 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:

IterationIndexCharacter takenReversed (so far)
14E"E"
23D"ED"
32O"EDO"
41C"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]

Download The App On Google Playstore

Everything you need to excel in your exams

Green Bridge CBT Mobile App
Personalized AI Learning Chat Assistant
200,000+ Exam Questions Across IGCSE, JAMB, WAEC & NECO
Over 3,900 Lesson Notes
Offline Support - Learn Anytime, Anywhere
Green Bridge Timetable
Literature Summaries & Potential Questions
Track Your Performance & Progress
In-depth Explanations for Comprehensive Learning