Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

codingbat Given a non-empty array containing an even number of elements, return

ID: 3816535 • Letter: C

Question

codingbat Given a non-empty array containing an even number of elements, return a new array consisting of the elements from the first half of the given array. For example, if the given array contains 6 elements, return a new array consisting of its first 3 elements. firstHalf([4, 7, 1, 5, 4, 2)) rightarrow [4, 7, 1] firstHalf([2, 8]) rightarrow (2) firstHalft([1, 2, 2, 1]) rightarrow [1, 2] int () firstHalf (int() nums) {int length = nums, length; for (int i = 0; (length; 1 ++){nums - new int(1);} return nums;}

Explanation / Answer

package org.students;

public class FirstHalfArray {

   public static void main(String[] args) {
  
       int arr[]={4,7,1,5,4,2};
      
       //Creating an first half array
       int firsthalfarr[]=new int[arr.length];
      
       //Displaying the elements in the actual array
       System.out.println("The elements in the array :");
       for(int i=0;i<arr.length;i++)
           System.out.print(arr[i]+" ");

       //calling the method which return the first half array
       firsthalfarr=firsthalf(arr);

       //Displaying the elements in the first half array
       System.out.println(" The First half elements :");
       for(int i=0;i<firsthalfarr.length;i++)
           System.out.print(firsthalfarr[i]+" ");

   }

   //This method will create the first half array from actual array and return
   private static int[] firsthalf(int[] arr) {
       int len=arr.length;
       int firsthalf[]=new int[len/2];
       for(int i=0;i<len/2;i++)
       {
           firsthalf[i]=arr[i];
       }
       return firsthalf;
   }

}

______________________

Output:

The elements in the array :
4 7 1 5 4 2
The First half elements :
4 7 1

_______________Thank You

Please rate me well.If you area satisfied.