Coding Bat – sameFirstLast

This exercise requires that the program analyze an array of integers and return TRUE if the array has a length greater than 1 and the first index is the same as the last index.

Here is the code that you start with:

public boolean sameFirstLast(int[] nums) {

}

As you can see, we have a single integer array named nums.

public boolean sameFirstLast(int[] nums) {
 if (nums.length >= 1){
   int first = nums[0];
   int last = nums[nums.length-1];
   if (first == last){
     return true;
   }
   return false;
   }
 return false;
}

We start on line 2 checking to see if the array has a minimum length of 1. If is does not, we skip to line 10 and return FALSE. If the Boolean on line 2 is true, we proceed to line 3.

We then declare an integer variable named “first” to retrieve the value of index 0 (line 3).

We then declare an integer variable named “last” to retrieve the value of the last letter (Line 4)

As was the case when working with strings, to retrieve the last index of the array, we must first calculate its length and then subtract 1 from the total length. This will give us the value of the last index of the array.

Lines 5 through 7 are the conditional Boolean looking to see if the first and last index are the same value. If the Boolean is TRUE, then TRUE is returned.

Leave a Reply

Your email address will not be published. Required fields are marked *