C# program to move zeros to end of array
To move zeros to the end of an array in C#, you can use a two-pointer approach. Here's an example program that moves zeros to the end of an array:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 0, 3, 0, 1, 0, 5, 0, 9 };
MoveZerosToEnd(numbers);
Console.WriteLine("Array after moving zeros to the end:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
public static void MoveZerosToEnd(int[] nums) {
int n = nums.Length;
int left = 0;
int right = 0;
while (right < n) {
if (nums[right] != 0) {
Swap(nums, left, right);
left++;
}
right++;
}
}
public static void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
In this program, we have an array of integers called numbers. We use the MoveZerosToEnd method to move zeros to the end of the array. The method uses two pointers, left and right, to track the positions of non-zero elements. It iterates through the array, and whenever a non-zero element is encountered, it swaps it with the element at the left pointer position and increments the left pointer. This effectively moves all the non-zero elements to the left side of the array. Finally, all the remaining elements after the left pointer position are zeros.
The program outputs the array after moving zeros to the end:
Array after moving zeros to the end:
3 1 5 9 0 0 0 0
In this case, the original array is { 0, 3, 0, 1, 0, 5, 0, 9 }. After moving the zeros to the end, the array becomes { 3, 1, 5, 9, 0, 0, 0, 0 }.