Coding Bat – firstLast6

This exercise requires that the program analyze an array of integers and return TRUE if either the first or last integer is a 6. The array is guaranteed to have a minimum length of 1.

Here is the code that you start with:

public boolean firstLast6(int[] nums) {

}

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

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

This solution utilizes a conditional if with the Boolean OR to solve the problem.

We start my declaring an integer variable named “first” to retrieve the value of index 0 (line 2).

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

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 4 through 6 are the conditional Boolean OR looking to see if either the first or last number are 6. If the Boolean is TRUE, then TRUE is returned.

Leave a Reply

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