Site icon

Program to Move zeros to end of integer array in java (example)

1. Example – move zeros to end of array in java (example)

Example 1:

Example 2:

2. Algorithm – move zeros to end of array in java (example)

3. Program – move zeros to the end of array in java (example)

package org.learn.arrays;

import java.util.Arrays;

public class MoveZerosToEnd {

	private static void moveZeroToEnd(int[] inputArray) {

		int index = 0;
		int nonZeros = 0;
		int length = inputArray.length;
		while (index < length) {

			if (inputArray[index] != 0) {
				inputArray[nonZeros++] = inputArray[index];
			}
			index++;
		}

		while (nonZeros < length) {
			inputArray[nonZeros++] = 0;
		}
		System.out.printf("%s", Arrays.toString(inputArray));
	}

	public static void main(String[] args) {

		int arr[] = { 2, 0, 5, 2, 0, 3, 1 };
		String sArray = Arrays.toString(arr);
		System.out.printf("1. Move zeros of array %s to end :", sArray);
		moveZeroToEnd(arr);
		
		arr = new int[]{ 1, 0, 2, 3, 0, 4, 0 };
		sArray = Arrays.toString(arr);
		System.out.printf("\n2. Move zeros of array %s to end :", sArray);
		moveZeroToEnd(arr);
	}
}

4. Output – move zeros to the end of array in java (example)

1. Move zeros of array [2, 0, 5, 2, 0, 3, 1] to end :[2, 5, 2, 3, 1, 0, 0]
2. Move zeros of array [1, 0, 2, 3, 0, 4, 0] to end :[1, 2, 3, 4, 0, 0, 0]
Exit mobile version