Write a java program to move all zeroes present in an array to the end

Another Java Program to send all the zero at the end of the array. Let’s practice another Java problem with the array to move all the zeroes present in an array to the end?

For that, we will traverse through the array to check if the element is zero. Then, we will traverse through the rest of the array to move the non-zero elements towards the left side and zero elements towards the right side of the array.

Sample Input:

Enter the no. of elements in an array:

5

Enter the array elements:

2 0 5 6 0

Output:

The final array is:

2 5 6 0 0

Write an algorithm to move all zeroes present in an array to the end

  1. First, we will take no. of elements present in an array and the array elements as input from the user.
  2. Next, we will create a for loop which runs from i=0 to i=n-1. 
  3. If the array element is found to equal to zero, we will check for upcoming non-zero no. For this, we will create a for loop which runs from j=i+1 to j=n-1. If the array element is found to be a non-zero no., we will replace the previously found array element  ( i.e. ar[i] ) with the newly found array element ( i.e. ar[j] ). And make the newly found array element equal to zero ( i.e. ar[j]=0 ). Once we have found such an element, we will break the inner for loop.
  4. The array thus obtained is the array that has all its zeroes moved to its right end. We will just simply print the array.

Program to move all zeroes present in an array to the end

import java.util.Scanner;
public class MoveZero 
{
    public static void main(String[] args) 
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the no. of elements in array:");
        int n=sc.nextInt();
        int ar[]=new int[n];
        System.out.println("Enter the array elements:");
        for(int i=0;i<n;i++) ar[i]=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            if(ar[i]==0)
            {
                for(int j=i+1;j<n;j++)
                {
                    if(ar[j]!=0)
                    {
                        ar[i]=ar[j];
                        ar[j]=0;
                        break;
                    }
                }
            }
        }
        System.out.println("The final array is:");
        for(int i=0;i<n;i++) System.out.print(ar[i]+" ");
    }
}

Output: