Finding the longest palindrome in an array In C

Longest palindrome in an array in C

Finding the longest palindrome in an array

In this page we will learn how to Find the longest palindrome in an array in C language. Before going to that lets know about what is palindrome, Palindrome is a number or string which is same even if we reverse it. Few examples are MADAM, MOM, DAD, ….

First we will sort the array, then iterate over it and find each element is palindrome or not. From this we can find longest or maximum palindrome number in an array.

Let’s see the algorithm and Code to Find the longest palindrome in an array in C.

Longest palindrome in an array

Algorithm:

  • First take the value N , size of the array and elements of the array from the user. And create a variable that keeps the track of the maximum palindrome number in the given array.
  • Sort the array.
  • Traverse the sorted array and check for every ith value, that it is palindrome or not. If the ith value of an array is  palindrome than we will update the variable.
  • After traversing the entire array we will get our maximum palindrome number.

In this we used three functions , those are

  • isPalindrome( )
  • swap( )
  • sort( )

isPalindrome()

This function returns 1 if the input number(integer) is palindrome, if it is not palindrome then it will return 0.

swap( )

Swap function is used to swap two elements. This function is used in sort( ) function

sort( )

sort( ) function is used to sort an input array in ascending order. We can implement any algorithm in sort function but here we used selection sort.

C Code:

#include <stdio.h>

int isPalindrome (int N)
{           

  int rev = 0, rem;

  int temp = N;

  while (temp)
    {
      rem = temp % 10;
      rev = rev * 10 + rem;
      temp /= 10;
    }

  if (N == rev)
    return 1;

  return 0;
}
void swap(int* xp, int* yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
void sort(int arr[], int n)
{
    int i, j, m;
    for (i = 0; i < n - 1; i++) {
        m= i;
        for (j = i + 1; j < n; j++)
            if (arr[j] < arr[m])
                m = j;
        swap(&arr[m], &arr[i]);
    }
}
int main ()
{

  int N;        
  printf("Enter the size of the array: ");
  scanf("%d",&N);

  int A[N]; 
    
  printf("\nInput the elements of the array: ");
 
  for (int i = 0; i < N; i++)
     scanf("%d",&A[i]);

  sort (A,N);       

  int result;       

  for (int i = 0; i < N; i++)
    {
      if (isPalindrome (A[i]))
        result = A[i];
    }

  printf("\nThe longest palindrome number is : %d",result);
return 0;
}

Input:

Enter the size of the array: 
5
Input the elements of the array:
20 19 222 1221 89798

Output:

The longest palindrome number is : 89798