This code defines a function `moveZeroes` that moves all zero...

May 18, 2025 at 12:45 PM

#include <iostream> using namespace std; void moveZeroes(int arr[], int n) { int insertPos = 0; // Move non-zero elements to the front for (int i = 0; i < n; ++i) { if (arr[i] != 0) { arr[insertPos++] = arr[i]; } } // Fill the rest with 0s while (insertPos < n) { arr[insertPos++] = 0; } } int main() { int arr[] = {0, 1, 0, 3, 12}; int n = sizeof(arr) / sizeof(arr[0]); moveZeroes(arr, n); cout << "After moving zeroes: "; for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } cout << endl; return 0; }

This code defines a function moveZeroes that moves all zero elements in an array to the end while maintaining the relative order of the non-zero elements. Here's what the code does in detail:

Step-by-step Explanation:

  1. The moveZeroes function takes two parameters:

    • arr: The array to process.
    • n: The size of the array.
  2. Inside the moveZeroes function:

    • A variable insertPos is initialized to 0. This keeps track of the position to place the next non-zero element.

    • A loop iterates through all elements of the array:

      • If the current element is not zero (arr[i] != 0), it is moved to the position indicated by insertPos, and insertPos is incremented.
    • After processing all elements, insertPos points to the position where zeros should start. A while loop then fills the rest of the array (from insertPos to the end) with zeros.

  3. In the main function:

    • A test array arr with elements {0, 1, 0, 3, 12} is defined.
    • The size of the array (n) is computed.
    • The moveZeroes function is called to process the array.
  4. After the moveZeroes function processes the array:

    • The array is updated such that all zeros are moved to the end, and the relative order of the non-zero elements remains unchanged.
    • The updated array is printed using a loop.

Example Execution:

For the input array {0, 1, 0, 3, 12}, the steps are:

  1. Non-zero elements {1, 3, 12} are moved to the front of the array.
  2. The remaining positions are filled with zeros.
  3. Final array after processing: {1, 3, 12, 0, 0}.

Output:

After moving zeroes: 1 3 12 0 0

Summary:

The code reorders the input array so that all zeros are moved to the end, while preserving the order of all non-zero elements.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node