Programming Basics (Pseudocode Tracing)
Array indices start at 1, and + concatenates strings. What is the value of r after the following program runs?
string array: s ← {"S", "T", "O", "P"}
string: r ← ""
for (i from 1 to length(s) step 1)
r ← s[i] + r
endfor
- APOTS
- BPOT
- CSTOP
Show answer and explanation
Answer: A. POTS
r ← s[i] + r adds each new character to the front (left) of r. r changes to "S", "TS", "OTS" and "POTS", so the characters end up in reverse order. Writing r ← r + s[i] would add each character to the end, giving "STOP", the same as the original.
- A. Correct. Characters are added to the front, giving the reverse, POTS.
- B. This is the result of starting the loop at 2. The first character "S" is also concatenated.
- C. This is the result of concatenating at the end, as in r ← r + s[i].
Continue: 9 more Programming Basics (Pseudocode Tracing) questions