0
0
CProgramBeginner · 2 min read

C Program to Move Zeros to End of Array

In C, you can move zeros to the end of an array by iterating through the array, copying non-zero elements forward using a count index, and then filling the rest with zeros; for example, use a loop to copy non-zero elements to the front and then fill zeros from count to the end.
📋

Examples

Inputarr = {0, 1, 0, 3, 12}
Outputarr = {1, 3, 12, 0, 0}
Inputarr = {1, 2, 3, 4, 5}
Outputarr = {1, 2, 3, 4, 5}
Inputarr = {0, 0, 0, 0}
Outputarr = {0, 0, 0, 0}
🧠

How to Think About It

To move zeros to the end, scan the array from start to end and keep track of the position to place the next non-zero element. When you find a non-zero, place it at that position and move the position forward. After processing all elements, fill the remaining positions with zeros.
📐

Algorithm

1
Initialize a variable count to 0 to track the position for non-zero elements.
2
Loop through each element of the array.
3
If the current element is not zero, copy it to the position indicated by count and increment count.
4
After the loop, fill the array from position count to the end with zeros.
5
Return or print the modified array.
💻

Code

c
#include <stdio.h>

void moveZerosToEnd(int arr[], int n) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0) {
            arr[count++] = arr[i];
        }
    }
    while (count < n) {
        arr[count++] = 0;
    }
}

int main() {
    int arr[] = {0, 1, 0, 3, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    moveZerosToEnd(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Output
1 3 12 0 0
🔍

Dry Run

Let's trace the array {0, 1, 0, 3, 12} through the code

1

Initialize count

count = 0

2

Check arr[0]

arr[0] = 0, zero found, do nothing, count = 0

3

Check arr[1]

arr[1] = 1, non-zero, arr[count] = 1, count = 1

4

Check arr[2]

arr[2] = 0, zero found, do nothing, count = 1

5

Check arr[3]

arr[3] = 3, non-zero, arr[count] = 3, count = 2

6

Check arr[4]

arr[4] = 12, non-zero, arr[count] = 12, count = 3

7

Fill zeros from count to end

arr[3] = 0, arr[4] = 0

Iterationarrcount
Start{0, 1, 0, 3, 12}0
i=0{0, 1, 0, 3, 12}0
i=1{1, 1, 0, 3, 12}1
i=2{1, 1, 0, 3, 12}1
i=3{1, 3, 0, 3, 12}2
i=4{1, 3, 12, 3, 12}3
Fill zeros{1, 3, 12, 0, 0}5
💡

Why This Works

Step 1: Copy non-zero elements forward

We use count to track where to place the next non-zero element, ensuring all non-zero elements keep their order.

Step 2: Fill remaining positions with zeros

After placing all non-zero elements, the rest of the array is filled with zeros to move all zeros to the end.

🔄

Alternative Approaches

Swap zeros with next non-zero
c
#include <stdio.h>

void moveZerosToEnd(int arr[], int n) {
    int j = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            j++;
        }
    }
}

int main() {
    int arr[] = {0, 1, 0, 3, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    moveZerosToEnd(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
This method swaps zeros with non-zero elements in place, which can be more efficient if you want to minimize writes.
Create new array for non-zero elements
c
#include <stdio.h>
#include <stdlib.h>

void moveZerosToEnd(int arr[], int n) {
    int *temp = (int *)malloc(n * sizeof(int));
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0) {
            temp[count++] = arr[i];
        }
    }
    while (count < n) {
        temp[count++] = 0;
    }
    for (int i = 0; i < n; i++) {
        arr[i] = temp[i];
    }
    free(temp);
}

int main() {
    int arr[] = {0, 1, 0, 3, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    moveZerosToEnd(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
This approach uses extra memory to store results, which is simpler but uses O(n) space.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through the array once, so the time complexity is O(n), where n is the number of elements.

Space Complexity

The main approach modifies the array in place using only a few variables, so space complexity is O(1).

Which Approach is Fastest?

The in-place method with a count index is fastest and uses least memory. The swap method is also O(n) but may do more writes. The extra array method uses more memory and is slower.

ApproachTimeSpaceBest For
In-place count methodO(n)O(1)Efficient and stable order
Swap zeros with non-zeroO(n)O(1)Minimizes writes, order preserved
Using extra arrayO(n)O(n)Simpler code but uses extra memory
💡
Use a separate index to track where to place non-zero elements to keep the array stable and efficient.
⚠️
Beginners often overwrite elements without tracking positions, losing non-zero values or changing their order.