ProgrammingModerateSSC CGL Tier 2 · IBPS PO Mains

Scanning "abcab dab" as a string of letters, the procedure below counts the adjacent pairs that read "ab" (both letters next to each other, in order). The text is "abcabdab". What is printed?

Scanning "abcab dab" as a string of letters, the procedure below counts the adjacent pairs that read "ab" (both letters next to each other, in order). The text is "abcabdab". What is printed?
count = 0
for i = 0 to n - 2
    if s[i] == 'a' and s[i+1] == 'b' then count = count + 1
end for
Print count
  1. A. 0
  2. B. 3
  3. C. 8
  4. D. 2

Correct answer: B. 3

The ab pairs start at positions 0, 3 and 6, which gives 3. Counting the ba pairs gives 0, printing the length gives 8, and stopping the scan two early misses the final pair and gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic