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).
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));
}
}
Comments
Leave a comment