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}


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 

No comments:

Post a Comment