×

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

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 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.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.