ProgrammingHardTCS NQT · Wipro

How many occurrences of the two-letter string "ab" are in "abcabab"? Count them with this program.

How many occurrences of the two-letter string "ab" are in "abcabab"? Count them with this program.
#include <stdio.h>
int main(void) {
    const char *s = "abcabab";
    int c = 0;
    for (int i = 0; s[i] && s[i + 1]; i++)
        if (s[i] == 'a' && s[i + 1] == 'b') c++;
    printf("%d", c);
}
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 1

Correct answer: C. 3

The matches start at positions 0, 3 and 5 of abcabab, so there are three.

More C Programming questions

Exams that ask this topic