Move Zeros To End Of An Array | Java Programs

Output:

*** Move Zeros In An Array To End ***

Given array is: 1, 0, 2, 0, 3, 0, 4, 0, 5, 
Now it becomes: 1, 2, 3, 4, 5, 0, 0, 0, 0,

Click Here For Java Online Compiler

Solution:

public class MoveZerosToEnd {

    public static void main(String[] args) {
        System.out.println("*** Move Zeros In An Array To End ***" + "\n");
        int[] array = {1, 0, 2, 0, 3, 0, 4, 0, 5};
        int countZero = 0;
        System.out.print("Given array is: ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + ", ");
        }
        System.out.println();
        System.out.print("Now it becomes: ");
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 0) {
                countZero++;
            } else {
                System.out.print(array[i] + ", ");
            }
        }
        for (int i = 1; i <= countZero; i++) {
            System.out.print(0 + ", ");
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon