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 functionint palindrome(int arr[], int startIndex, int endIndex){// base caseif (startIndex >= endIndex) { //if the middle of array is reachedreturn 1;}// recursive caseif (arr[startIndex] == arr[endIndex]) { //compare if index value matchesreturn palindrome(arr, startIndex + 1, endIndex - 1);}//base caseelse {return 0; // if mismatch found}}// Driver codeint main(){int array[] = { 1, 2, 2, 2, 1 };//declare an arrayint n = sizeof(array) / sizeof(array[0]);//calculate the size of the arrayint startIndex=0;//define the starting indexint endIndex=n-1;//define the ending indexif (palindrome(array, startIndex, endIndex) == 1) //call recursive functioncout << "Array is a Palindrome";elsecout << "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