i want to remove 0 from an integer array.like if i have an array having element 2 2 1 1 1 0 1 1 2 1 0 1 ,i want this as
2 2 1 1 1 1 1 2 1 1,plz help me
This is one way to do it:
1. Loop through the array and for all 0's assign its value to -1
2. Store the number of elements that is to be removed, so you know the length of the new array.
3. Create a new array and copy all elements from the old array that is not equal to -1
It won't work if you allow negative integers though, but you can avoid that by storing the indices that is supposed to be deleted.
You could reuse the old array, by moving all elements one step 'left', but then the array will be to big.
if you are limited to using the premitive type of int as an array then you can do it this way:
1. loop through the array
2. if 0 is found then "shuffle" the preceeding elements by replacing the "0" element with the next element (if not zero).
3. count how many zeros were remove and create a new array of ints with size = orignal int array size - number of zeros remove
4. copy all elements from index = 0 to index = size-1, to the newly created array.
This is rather a very inefficient way to do it with arrays. I suggest you use an ArrayList or other data structures which have methods to remove elements.