Go to Top

Saturday 29 October 2011

To delete a value from an array

Question 65 : Write a program in Java to delete ONE value from an array.

Java Program :

class del
{
 int[] a;
 int n,p=-1;
 del(int[] arr,int num)
 {
     a=arr;
     n=num;
     search();
     del();
    }
    void search()
    {
        for(int i=0;i<a.length;i++)
        {
            if(a[i]==n)
            p=i;
        }
    }
    void del()
    {
        int b;
        if(p!=-1)
        {
            b=a[a.length-1];
            a[a.length-1]=a[p];
            a[p]=b;
            System.out.print("Array : { ");
            for(int i=0;i<a.length-1;i++)
            System.out.print(a[i]+" ");
            System.out.print("}");
        }
        else
        System.out.print("Error 404");
    }
}

1 comment:

  1. can you please post your programs with output.....cuz they are not getting executed. thank you!

    ReplyDelete

ShareThis