×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

Here, we are going to learn how to check a string is palindrome or not using recursion in C programming language?
Submitted by Nidhi, on July 15, 2021

Problem statement

Given a string, we have to check whether the given string is palindrome or not using recursion.

Checking a string is palindrome or not without using recursion

The source code to check a string is palindrome or not using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

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

// C program to check a string is palindrome or not
// using recursion

#include <stdio.h>
#include <string.h>

void isPalindrom(char str[], int index)
{
    int len = strlen(str) - (index + 1);

    if (str[index] == str[len]) {
        if (index + 1 == len || index == len) {
            printf("Given string is a palindrome\n");
            return;
        }
        isPalindrom(str, index + 1);
    }
    else {
        printf("Given string is not a palindrome\n");
    }
}

int main()
{
    char str[32] = { 0 };
    char rev[32] = { 0 };

    int cnt = 0;
    int flg = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    isPalindrom(str, 0);

    return 0;
}

Output

RUN 1:
Enter a string: malayalam
Given string is a palindrome

RUN 2:
Enter a string: abcdcba
Given string is a palindrome

RUN 3:
Enter a string: hello
Given string is not a palindrome

Explanation

In the above program, we created two functions isPalinfrom() and main() function. The isPalindrom() is a recursive function to check specified string is palindrome or not.

In the main() function, we read a string str from the user using the scanf() function. Then we called the isPalindrom() function to check string is palindrome or not and print the appropriate message on the console screen.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.