ProgrammingHardInfosys · Accenture pattern

What will be the output of the following pseudocode? (Strings are indexed from 0; swap exchanges two characters.)

What will be the output of the following pseudocode? (Strings are indexed from 0; swap exchanges two characters.)
String s = "ABCDEF"
Integer n = length(s)
for (i = 0 to n / 2 - 1)
    if (i mod 2 == 0)
        swap(s[i], s[n - 1 - i])
    end if
end for
Print s
  1. A. FEDCBA
  2. B. FBCDEA
  3. C. FBDCEA
  4. D. AEDCBF

Correct answer: C. FBDCEA

i runs 0, 1, 2. i = 0 swaps A and F → FBCDEA; i = 1 is odd, skipped; i = 2 swaps C and D → FBDCEA. A full reversal (FEDCBA) would need the swap at i = 1 too; FBCDEA stops after the first swap.

More Pseudocode and Code Tracing questions

Exams that ask this topic