Answer to Question #184704 in Java | JSP | JSF for salma wael

Question #184704

write a method called insert that inserts an element into an integer array. It should take 3 parameters: an int array, the number to be inserted and the index it should be inserted at. It should return a new array that has the element inserted at the index (the new array should have a length 1 longer than the original array).


1
Expert's answer
2021-04-23T13:18:56-0400
import java.util.Arrays;

public class temp{
  
   //method that takes in an int array and two other integers
   public static int[] insert(int[] arr, int num, int index) {
       //declaring a new array to store result that has size 1 more than arr
       int[] result=new int[arr.length+1];
       //j is used for traversal of arr
       int j=0;
       //we traverse result array
       for(int i=0;i<result.length;i++) {
           //if i is equal to index
           if(i==index)
               //we insert num into result
               result[i]=num;
           //else, we copy element of arr at i into result at j
           else {
               result[i]=arr[j];
               j++;
           }
       }
       //returning result array
       return result;
   }
  
   //main method
public static void main(String[] args) {
   //testing code
   int[] a = {1,2,3,4,5};
   int[] inserted = insert(a,9,0);
   System.out.println(Arrays.toString(inserted));
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS