Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to move all zeros in int array to the end with Java

1 Answer

0 votes
public class MyClass {
    static void move_zeros_to_end(int arr[]) { 
        int j = 0, len = arr.length;  
        
        for (int i = 0; i < len; i++) 
            if (arr[i] != 0) 
                arr[j++] = arr[i]; 
        
        while (j < len) 
            arr[j++] = 0; 
    } 
    public static void main(String args[]) {
       int[] arr= {0, 3, 4, 0, 6, 0, 0, 8, 9, 0}; 
        
        move_zeros_to_end(arr); 

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


/*
run:

3 4 6 8 9 0 0 0 0 0 

*/

 



answered Feb 25, 2019 by avibootz

Related questions

1 answer 131 views
1 answer 139 views
1 answer 168 views
1 answer 147 views
2 answers 151 views
1 answer 167 views
2 answers 130 views
...