×

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be placed to the right side of the array.

Example

Input

arr[] = {1, 2, 0, 4, 3, 0, 6, 0};

Output:

arr[] = {1, 2, 4, 3, 6, 0, 0, 0};

Explanation

All the non-zero elements are aligned to the left-hand side of the array without changing the sequence number

Input:

arr[]  = {1, 2, 0, 0, 0, 3, 5};

Output:

arr[] = {1, 2, 3, 5, 0, 0, 0};

Naive approach

  • Traverse the arr[] from left to right.
  • While traversing, maintain the count of non-zero elements. For every non-zero element, change arr[i] with arr[count].
  • Increment the count.
  • Now all non-zero elements have been shifted to the front and 'count' is set as the index of the first 0. Make all elements 0 from count to end.

C++ code

#include <iostream>
using namespace std;


// function to move zeros to the right 
void pushZerosTotheright(int arr[], int n)
{
	int count = 0; // Count of non-zero elements


	// Traverse the array. If element encountered is non-
	// zero, then replace the element at index 'count'
	// with this element
	for (int i = 0; i < n; i++)
		if (arr[i] != 0)
			arr[count++] = arr[i]; // here count is
								// incremented


	// Now all non-zero elements have been shifted to
	// front and 'count' is set as index of first 0.
	// Make all elements 0 from count to end.
	while (count < n)
		arr[count++] = 0;
}




int main()
{
	int arr[] = {1, 2, 0, 4, 3, 0, 6, 0};
	int n = sizeof(arr) / sizeof(arr[0]); // find size of the array 
	pushZerosTotheright(arr, n); // call the function 
	cout << "The output array rearranged is :\n";
	for (int i = 0; i < n; i++)
		cout << arr[i] << " "; // print the elements 
	return 0;
}

Output

The output array rearranged is :
1 2 4 3 6 0 0 0 

C code

#include <stdio.h>


// function to move zeros to the right 
void pushZerosTotheright(int arr[], int n)
{
	int count = 0; // Count of non-zero elements


	// Traverse the array. If element encountered is non-
	// zero, then replace the element at index 'count'
	// with this element
	for (int i = 0; i < n; i++)
		if (arr[i] != 0)
			arr[count++] = arr[i]; // here count is
								// incremented


	// Now all non-zero elements have been shifted to
	// front and 'count' is set as index of first 0.
	// Make all elements 0 from count to end.
	while (count < n)
		arr[count++] = 0;
}




int main()
{
	int arr[] = {1, 2, 0, 4, 3, 0, 6, 0};
	int n = sizeof(arr) / sizeof(arr[0]); // find size of the array 
	pushZerosTotheright(arr, n); // call the function 
	printf( "The output array rearranged is :\n");
	for (int i = 0; i < n; i++)
		printf("%d ",arr[i]); // print the elements 
	return 0;
}

Output

The output array rearranged is :
1 2 4 3 6 0 0 0 

Time complexity - O(n)

Space complexity - O(1)

Approach 2

The optimised approach checks the non-zero element and exchange with the arr[i] positioned element.

Algorithm

moveZerosToEndOfTheArray(arr, n)

    Initialize count = 0

    for i = 0 to n-1

        if (arr[i] != 0) then

            swap(arr[count++], arr[i])

C++ code

#include <iostream>
using namespace std;


// function to move zeros to the right 
void pushZerosTotheright(int arr[], int n)
{


		// Count of non-zero elements
    int count = 0;
 
    // Traverse the array. If arr[i] is non-zero, then
    // swap the element at index 'count' with the
    // element at index 'i'
    for (int i = 0; i < n; i++)
        if (arr[i] != 0)
            swap(arr[count++], arr[i]);
}




int main()
{
	int arr[] = {1, 2, 0, 4, 3, 0, 6, 0};
	int n = sizeof(arr) / sizeof(arr[0]); // find size of the array 
	pushZerosTotheright(arr, n); // call the function 
	cout << "The output array rearranged is :\n";
	for (int i = 0; i < n; i++)
		cout << arr[i] << " "; // print the elements 
	return 0;
}

Output

The output array rearranged is :
1 2 4 3 6 0 0 0 

Time complexity - O(n)

Space complexity - O(1)


Related Topics

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.