filter every other element of an array in csharp

To filter every other element of an array in C#, you can use a simple iteration with the modulo operator %. Here's an example code block:

main.cs
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] filteredArray = new int[array.Length / 2 + 1]; // add 1 to handle odd-length arrays

int j = 0;
for (int i = 0; i < array.Length; i += 2)
{
    filteredArray[j++] = array[i];
}

foreach (int value in filteredArray)
{
    Console.Write(value + " ");
}
// Output: 1 3 5 7 9
337 chars
15 lines

Here, we first create an integer array array with some sample values. We also create another integer array filteredArray with half the length of array (rounded up) to account for the possible odd length.

We then use a for loop to iterate through every other element of array (starting from index 0) and add them to filteredArray. The index of filteredArray is incremented at each iteration. We use the modulo operator % to check if the current index is even.

Finally, we use a foreach loop to print the filtered array to the console.

gistlibby LogSnag