
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to move all the zeros to the end of the array from the given array of integer numbers using C#?
Create a method MoveZeros, traverse through the array and count the number of Zeros in the array. Based on the count size make all the final cells to zero. Return without processing if the array length is null or empty. The final result will be in nums Array. Time complexity is O(N) because we are traversing through the array once.
Time complexity − O(N)
Space complexity − O(1)
Example
public class Arrays{ public void MoveZeros(int[] nums){ if (nums == null || nums.Length == 0){ return; } int count = 0; for (int i = 0; i < nums.Count(); i++){ if (nums[i] != 0){ nums[count] = nums[i]; count++; } } for (int i = count; i < nums.Length; i++){ nums[i] = 0; } } } static void Main(string[] args){ int[] nums = { 0, 1, 0, 3, 12 }; s.MoveZeros(nums); foreach (var item in nums){ Console.WriteLine(item); } }
Output
[1,3,12,0,0]
- Related Articles
- Move All the Zeros to the End of Array in Java
- Move all zeroes to end of the array using List Comprehension in Python
- Move all zeroes to end of array in C++
- Move all zeros to start and ones to end in an Array of random integers in C++
- Move all zeros to the front of the linked list in C++
- Write an algorithm that takes an array and moves all of the zeros to the end JavaScript
- Python Program to move numbers to the end of the string
- How to find the minimum number of jumps required to reach the end of the array using C#?
- C# Program to skip elements of an array from the end
- How do you separate zeros from non-zeros in an integer array using Java?
- How to find the length of the longest continuous increasing subsequence from an array of numbers using C#?
- Smallest integer > 1 which divides every element of the given array: Using C++
- How to find the target sum from the given array by backtracking using C#?
- Check if the given array contains all the divisors of some integer in Python
- How to move the pointer of a ResultSet to the end of the table using JDBC?

Advertisements