ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
int isPalindrome(const char *s, int left, int right) {
    if (left >= right) return 1;
    if (s[left] != s[right]) return 0;
    return isPalindrome(s, left + 1, right - 1);
}
int main(void) {
    const char *str = "racecar";
    printf("%d", isPalindrome(str, 0, 6));
}
  1. A. 0
  2. B. 7
  3. C. Undefined behaviour: recursion depth depends on string length
  4. D. 1

Correct answer: D. 1

isPalindrome compares characters from both ends inward, recursing only while they match. "racecar" reads the same forwards and backwards, so every comparison succeeds all the way until left >= right (meeting in the middle), returning 1 (true).

More C Programming questions

Exams that ask this topic