Q:

Java program to move all zero at the end of the array

belongs to collection: Java Array Programs

0

Given an integer array with zeros (0’s) and we have to move all zeros at the end of the array using java program.

Example:

    Input array: 5, 1, 6, 0, 0, 3, 9, 0, 6, 7, 8, 12, 10, 0, 2
    After moving 0 at the end 
    Output array: 5, 1, 6, 3, 9, 6, 7, 8, 12, 10, 2, 0, 0, 0, 0

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to move zeros at the end of the array in java

public class MoveZeros {
  static void moveZeroElementToEnd(int[] arr) {
    // declare and initialize.
    int size = arr.length;
    int count = 0;

    // access all array elements.
    for (int i = 0; i < size; i++) {
      if (arr[i] != 0) {
        arr[count++] = arr[i];
      }
    }

    while (count < size)
      arr[count++] = 0;
  }

  public static void main(String[] args) {
    // take default elements in array.
    int[] arr = {
      5,
      1,
      6,
      0,
      0,
      3,
      9,
      0,
      6,
      7,
      8,
      12,
      10,
      0,
      2
    };
    moveZeroElementToEnd(arr);

    // print elements after moving 0's to end
    System.out.print("Array after moving zeros to end : ");

    for (int i = 0, size = arr.length; i < size; i++)
      System.out.print(arr[i] + " ");
  }
}

Output

    Array after moving zeros to end : 5 1 6 3 9 6 7 8 12 10 2 0 0 0 0 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to delete a specific element from a o... >>
<< Java program to find differences between minimum a...