Go to Top

Wednesday 5 October 2011

To insert a value in an array

Question 57 : Write a program in Java to insert a value in an array.

Java Program :

class insert_val
{
 int[] a;
 int n,p;
 insert_val(int[] arr,int number,int position)
 {
     a=new int[arr.length+1];
     for(int i=0;i<arr.length;i++)
     a[i]=arr[i];
     n=number;
     p=position-1;
     check();
    }
    void check()
    {
        if(p>=0 && p<a.length)
        insert();
        else
        System.out.print("Array Index Out of Bounds Exception");
    }
    void insert()
    {
        a[a.length-1]=a[p];
        a[p]=n;
        System.out.print("Updated Array : ");
        array.display(a);
    }
}

No comments:

Post a Comment

ShareThis