Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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++
#includeusing namespace std; void moveZeroesToEnd(int arr[], int n) { int index = 0; for (int i = 0; i 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
Advertisements
