-1

The above code is for inserting an element in an array. I tried changing the length of an array to 9 but still the issue persist.

public class Array1 {
    public static int[] insertX (int n,int x,int pos,int arr[]) {
        
        int newarr[] = new int[n+1];
      
        for(int i=0; i<i+1;i++) {
            if(i < pos -1) {
                newarr[i]=arr[i];
            }
            else if(i==pos-1) {
                newarr[i]=x;
            }
            else
            {
                newarr[i]= arr[i-1];
            }
            
        }
        return newarr;
        
        
    }
    public static void main(String[] args) {
        
        int n=10;
        int arr[] = {1,2,3,4,5,6,7,8,9,10}; 
        System.out.println("Initial array"+ " " + Arrays.toString(arr));
        int x=50;
        int pos =5;
        arr = insertX(n,x,pos,arr);
        System.out.println("Array with inserted number"+ " " + Arrays.toString(arr));
    }

}

 
Anushree P
  • 31
  • 2
  • 9

1 Answers1

2

You need to change your loop end condition:

for(int i=0; i<newarr.length;i++) 

Condition i<i+1 is always true, so your lop will never end.

Example:

  • i=0; then 0<0+1;
  • i=2; then 2<2+1;

When the i index will reach 10, there is no value in newarr for this index. Max index is 9.. This will cause IndexOutOfBoundsException.

Its safer to use array.length, this way you will not make this exception again.

Beri
  • 11,470
  • 4
  • 35
  • 57