w3resource

Java: Move all 0's to the end of an array

Java Array: Exercise-26 with Solution

Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array elements.

Pictorial Presentation:

Java Array Exercises: Move all 0's to the end of an array

Sample Solution:

Java Code:

// Import the java.util package to use utility classes, including Arrays.
import java.util.*;

// Define a class named Exercise26.
public class Exercise26 {
    // The main method for executing the program.
    public static void main(String[] args) throws Exception {
        // Declare and initialize an array of integers.
        int[] array_nums = {0, 0, 1, 0, 3, 0, 5, 0, 6};
        int i = 0;

        // Print the original array.
        System.out.print("\nOriginal array: \n");
        for (int n : array_nums)
            System.out.print(n + "  ");

        // Use a loop to move zeros to the end of the array.
        for (int j = 0, l = array_nums.length; j < l;) {
            if (array_nums[j] == 0)
                j++;
            else {
                // Swap the non-zero element with the first available zero.
                int temp = array_nums[i];
                array_nums[i] = array_nums[j];
                array_nums[j] = temp;
                i++;
                j++;
            }
        }

        // Fill the remaining positions with zeros.
        while (i < array_nums.length)
            array_nums[i++] = 0;

        // Print the array after moving zeros to the end.
        System.out.print("\nAfter moving 0's to the end of the array: \n");
        for (int n : array_nums)
            System.out.print(n + "  ");
        System.out.print("\n");
    }
}

Sample Output:

                                                                              
Original array:                                                        
0  0  1  0  3  0  5  0  6                                              
After moving 0's to the end of the array:                              
1  3  5  6  0  0  0  0  0 

Flowchart:

Flowchart: Java exercises: Move all 0's to the end of an array

Java Code Editor:

Previous: Write a Java program to find common elements from three sorted (in non-decreasing order) arrays.
Next: Write a Java program to find the number of even and odd integers in a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/array/java-array-exercise-26.php