...

/

Solution Review 1: Find if the Array is a Palindrome

Solution Review 1: Find if the Array is a Palindrome

This lesson gives a detailed solution review of how to find if the array is a palindrome.

Solution: Is the array a palindrome?

Press + to interact
#include <iostream>
using namespace std;
// Recursive function
int palindrome(int arr[], int startIndex, int endIndex)
{
// base case
if (startIndex >= endIndex) { //if the middle of array is reached
return 1;
}
// recursive case
if (arr[startIndex] == arr[endIndex]) { //compare if index value matches
return palindrome(arr, startIndex + 1, endIndex - 1);
}
//base case
else {
return 0; // if mismatch found
}
}
// Driver code
int main()
{
int array[] = { 1, 2, 2, 2, 1 };//declare an array
int n = sizeof(array) / sizeof(array[0]);//calculate the size of the array
int startIndex=0;//define the starting index
int endIndex=n-1;//define the ending index
if (palindrome(array, startIndex, endIndex) == 1) //call recursive function
cout << "Array is a Palindrome";
else
cout << "Array is not Palindrome";
return 0;
}

Understanding the code

A recursive code can be broken down into two parts. The recursive function and the main where the function is called.

Driver Function

The driver code is from line 21 to line 33

  • In the driver code, an array is defined.
  • The size of the array is defined on line 25.
  • The function
...