Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Check whether a given String is Palindrome or Not using Recursion Function


Write a C program to check if a string is a palindrome or not using recursion function

  • The function is_palindrome() uses recursion to check if a string reads the same forwards and backwards.
  • If the start index is greater than or equal to the end index, it returns true (base case for single/mid character).
  • If the characters at start and end indices don't match, the string is not a palindrome.
  • If characters match, it recursionly checks the next pair inward (start+1, end-1).
Example : pgm.c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool is_palindrome(const char *str, int start, int end) {
    // Base case: if the string has 0 or 1 characters
    if (start >= end)
        return true;
    // If the characters at start and end are different, not a palindrome
    if (str[start] != str[end])
        return false;
    // Recursion call
    return is_palindrome(str, start + 1, end - 1);
}

int main() {
    const char *word1 = "radar";
    const char *word2 = "hello";

    printf("%s: %s\n", word1, is_palindrome(word1, 0, strlen(word1) - 1) ? "Palindrome" : "Not Palindrome");
    printf("%s: %s\n", word2, is_palindrome(word2, 0, strlen(word2) - 1) ? "Palindrome" : "Not Palindrome");

    return 0;
}

Output :

radar: Palindrome
hello: Not Palindrome