
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Move all zeroes to end of array in C++
Given array with multiple zeroes in it. We have to move all the zeroes in the array to the end. Let's see an example.
Input
arr = [4, 5, 0, 3, 2, 0, 0, 0, 5, 0, 1]
Output
4 5 3 2 5 1 0 0 0 0 0
Algorithm
Initialise the array.
Initialise an index to 0.
Iterate over the given array.
If the current element is not zero, then update the value at the index with the current element.
Increment the index.
Write a loop that iterates from the above index to n
Update all the elements to 0.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; void moveZeroesToEnd(int arr[], int n) { int index = 0; for (int i = 0; i < n; i++) { if (arr[i] != 0) { arr[index++] = arr[i]; } } while (index < n) { arr[index++] = 0; } } int main() { int arr[] = {4, 5, 0, 3, 2, 0, 0, 0, 5, 0, 1}; int n = 11; moveZeroesToEnd(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
Output
If you run the above code, then you will get the following result.
4 5 3 2 5 1 0 0 0 0 0
- Related Articles
- Move all zeroes to end of the array using List Comprehension in Python
- Move All the Zeros to the End of Array in Java
- Moving all zeroes present in the array to the end in JavaScript
- Move all zeros to start and ones to end in an Array of random integers in C++
- Move Zeroes in Python
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Minimum move to end operations to make all strings equal in C++
- In-place Move Zeros to End of List in Python
- In-place Algorithm to Move Zeros to End of List in JavaScript
- Python Program to move numbers to the end of the string
- Move first element to end of a given Linked List in C++
- Move the first row to the end of the JTable in Java Swing
- Double the first element and move zero to end in C++ Program
- C++ program to find minimum number of steps needed to move from start to end
- How to move the pointer of a ResultSet to the end of the table using JDBC?

Advertisements