Palindrome Using Recursion

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to check if a given number is a palindrome using recursion in C programming language. A Palindrome is a sequence that if reversed looks identical to the original sequence Eg : abba, level, 999, etc.

Create a main function

In the main.c file, create a function main that has the following code block. It receives an integer from the user and then calls the isPal function to check if the number is a palindrome or not.

#include<stdio.h>
int isPal(int );
int n;
int main()
{
  printf("\nEnter a number to check for Palindrome: ");
  scanf("%d", &n);
  isPal(n);
  return 0;
}

Create the isPal function using recursion.

The isPal function will take an integer as its argument and return whether itโ€™s a palindrome or not. It uses recursion to check the palindrome condition. If the palindrome condition satisfies, it will return a value of 1, indicating that the number entered is Palindrome; otherwise, it will return 0.

int isPal(int aj)
{
    static int sum = 0;
    if(aj != 0)
    {
        sum = sum *10 + aj%10;
        isPal(aj/10);
    }
    else if(sum == n)
        printf("%d is palindrome.\n",n);
    else
        printf("%d is not palindrome.\n",n);
    return 0;
}

Compile and Run the code

Compile the code using the following command: gcc -o main main.c

Run the code using the following command: ./main

Enter the number that needs to be checked whether it is a palindrome or not.

Program Output

The output of the program will show if the provided input number is a palindrome or not.

Summary

In this lab, we learned how to check if a given number is a palindrome using recursion with a C program. Palindrome is an important concept in computer science and is used in various applications, including string matching algorithms. We hope this lab has helped in understanding recursion and C programming language concepts.

Other C Tutorials you may like