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 C++

1 Answer

0 votes
#include <iostream>
 
using namespace std;
 
void move_zeros_to_end(int arr[], int len) {
    int j = 0;
  
    for (int i = 0; i < len; i++) {
        if (arr[i] != 0)
            arr[j++] = arr[i];
    }
  
    while (j < len)
        arr[j++] = 0;
}
     
int main(int argc, char **argv) 
{
    int arr[] = { 0, 3, 4, 0, 6, 0, 0, 8, 9, 0 };
    int len = sizeof(arr) / sizeof(arr[0]);
  
    move_zeros_to_end(arr, len);
  
    for (int i = 0; i < len; i++)
        cout << arr[i] << " ";
  
    return 0; 
}
      
        
/*
run:
      
3 4 6 8 9 0 0 0 0 0
   
*/

 



answered Feb 25, 2019 by avibootz
edited Feb 25, 2019 by avibootz

Related questions

2 answers 151 views
1 answer 131 views
1 answer 139 views
1 answer 168 views
1 answer 143 views
1 answer 103 views
1 answer 128 views
...