...

/

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 ...

Access this course and 1400+ top-rated courses and projects.