Monday, 9 September 2019

Java code to move all zero of an integer array to the end of the array

          In this post, we will implement a java code to move all zero's of given array integers to an end of an array. Given array is mixed of zero's and non zero's numbers.

For example,

Input array is = {2,1,0,3,5,0,9,0}
Output array is = {2,1,3,5,9,0,0,0}

ZeroNonZerosSeparate.java,

package com.example.demo;

public class ZeroNonZerosSeparate {
 
          public static void main(String[] args) {
  
                   int[] nums = {2,1,0,3,5,0,9,0};
  
                   int index = 0;
                   
                   for (int i = 0; i<nums.length; i++) {
                         if (nums[i] != 0) {
                                nums[index] = nums[i];
                                index++;
                         }
                   }
  
                   while (index < nums.length) {
                          nums[index] = 0;
                          index++;
                   }
  
                   for (int i = 0; i<nums.length; i++) {
                          System.out.print(nums[i]+" ");
                   }
           }

 }

Output:-
2 1 3 5 9 0 0 0 

Related Posts:-
1) Difference between NoClassDefFoundError and ClassNotFoundException in Java
2) Swap two variables without using third variable in Java
3) Sort a binary array using one traversal in Java
4) Java program to find second largest number in an array
5) Java Code to Print the Numbers as Pyramid - Examples
6) Java Program to find the Missing Number in an Array
7) Java program to print the first n prime numbers
8) Write a Java program to print the Floyd's triangle

No comments:

Post a Comment