Write a program to Move all zero at the end of the array


The code MoveAll_ZeroEnd is an implementation of a method to move all the zero elements in an integer array to the end of the array while keeping the non-zero elements in their original order.

The method moveZeroElementToEnd takes an integer array a as input and modifies it to move all the zero elements to the end of the array. It first initializes two variables s and count to the length of the input array and 0 respectively. Then, it iterates over the input array using a for-loop and if the current element is non-zero, it assigns the current element to the count-th position of the input array and increments count. After this loop, all the non-zero elements have been moved to the beginning of the array, and the count variable holds the number of non-zero elements in the array. The method then iterates over the remaining positions of the array starting from the count-th position and sets all the elements to 0, effectively moving all the zero elements to the end of the array.

In the main method, an integer array a is initialized with some values, and the moveZeroElementToEnd method is called with this array as input. Finally, the contents of the modified array are printed to the console using another for-loop.

Source Code

public class MoveAll_ZeroEnd
{
	static void moveZeroElementToEnd(int[] a)
	{
		int s = a.length;
		int count = 0;
 
		for (int i = 0; i < s; i++)
		{
			if (a[i] != 0)
			{
				a[count++] = a[i];
			}
		}
 
		while (count < s)
		{
			a[count++] = 0;
		}
	}
 
	public static void main(String[] args)
	{	
		int[] a = {1,0,45,34,0,67,2,0,6,67,45,2,0,10};
		moveZeroElementToEnd(a);
 
		System.out.print("Array after Moving Zeros to End : ");
 
		for (int i = 0, s = a.length; i < s; i++)
		{
			System.out.print(a[i] + " ");
		}
	}
}

Output

Array after Moving Zeros to End : 1 45 34 67 2 6 67 45 2 10 0 0 0 0

Example Programs