Answer:
Here is the JAVA program:
class Main {
static boolean isPalindrome(int array[], int starting, int ending) { /*a boolean method that takes an integer-valued array, and a pair of integers representing the starting and ending indexes of the portion of the array to be tested for being a palindrome */
if (starting >= ending) { //base case
return true; } //returns true
if (array[starting] == array[ending]) { //recursive case
return isPalindrome(array, starting + 1, ending - 1); } //calls isPalindrome recursively to find out palindrome
else {
return false; } } //returns false if array is not palindrome
public static void main (String[] args) { //start of main function
int array[] = { 1,2,3,2,1}; //creates an array
int size = array.length; //computes the size of array
System.out.print(isPalindrome(array, 0, size - 1)); } } //calls method to test array for being a palindrome
Explanation:
The program works as follows:
array = { 1,2,3,2,1}
starting = 0
ending = size-1 = 5-1 = 4
if (starting >= ending) condition evaluates to false because starting i.e. 0 is not greater or equal to ending i.e. 4. So the program moves to the next if part
if (array[starting] == array[ending])
This becomes:
if (array[0] == array[4])
The element at 0th index is the first element of the array i.e. 1 and the element at 4th index of array is the last element of array i.e. 1. So both these elements are equal so the following statement executes:
return isPalindrome(array, starting + 1, ending - 1);
Now the starting and ending become:
starting+1 = 0+1 = 1
ending-1 = 3
if (starting >= ending) base condition evaluates to false because starting is not greater or equal to ending. So the program moves to the next if part
if (array[starting] == array[ending])
This becomes:
if (array[1] == array[3])
The element at 1st index is 2 and the element at 3rd index of array is 2. So both these elements are equal so the following statement executes:
return isPalindrome(array, starting + 1, ending - 1);
Now the starting and ending become:
starting+1 = 1+1 = 2
ending-1 = 2
if (starting >= ending) base condition evaluates to true because starting is equal to ending. So the following statement executes:
return true;
This means the function returns true and this shows that array is a palindrome.
The screenshot of the program and its output is attached.