There is a standard algorithm std::stable_partition , declared in the header file <algorithm> , which allows you to perform the task in one line.
Below is a demonstration program.
#include <iostream> #include <algorithm> #include <iterator> int main() { int a[] = { 2, 0, 3, 4, 0, 0, 8 }; for (int x : a) std::cout << x << ' '; std::cout << std::endl; std::stable_partition(std::begin(a), std::end(a), [](int x) { return x != 0; }); for (int x : a) std::cout << x << ' '; std::cout << std::endl; }
Its output to the console:
2 0 3 4 0 0 8 2 3 4 8 0 0 0
If you need to solve a problem using cycles, then you can, for example, use such a straightforward approach, iterating over elements from the end of an array
#include <iostream> int main() { int a[] = { 2, 0, 3, 4, 0, 0, 8 }; const size_t N = sizeof(a) / sizeof(*a); for (int x : a) std::cout << x << ' '; std::cout << std::endl; for (size_t i = N, m = N; i != 0; i--) { if (a[i] == 0) { int item = a[i - 1]; for (size_t j = i; j != m; j++) { a[j - 1] = a[j]; } a[--m] = item; } } for (int x : a) std::cout << x << ' '; std::cout << std::endl; }
The output of this program to the console will be the same as shown above:
2 0 3 4 0 0 8 2 3 4 8 0 0 0