[Solved] How to SkipEvery 3rd element of the array [closed]


You can try Linq in order to filter out the items and create a new array:

  int[] numbers = new int[] { 7, 2, 24, 69, 101, 42, 84, 100, 72 };

  int[] skipped = numbers
    .Select((item, index) => (index + 1) % 4 != 0 ? item : -1)
    .ToArray();

If you want to modify existing array, a simple loop will do

  for (int i = 3; i < numbers.Length; i += 4)
    numbers[i] = -1; 

Finally, let’s have a look at the outcome (skipped):

  string report = string.Join(" ", skipped
    .Select((item, index) => $"[{index}]{item}"));

  Console.Write(report);

Outcome:

  [0]7 [1]2 [2]24 [3]-1 [4]101 [5]42 [6]84 [7]-1 [8]72

Edit: Your current code amended:

static int[] SkipEvery(int[] numbers, int skip) {
  int[] skipped = new int[numbers.Length];

  for (int i = 0; i < numbers.Length; i++) {
    if ((i + 1) % (skip + 1) == 0) { // check indexes - i, not values - numbers[i]
      skipped[i] = -1;               // well, you have to skip!   
    }
    else {
      skipped[i] = numbers[i];
    }
  }
  return skipped;
}

solved How to SkipEvery 3rd element of the array [closed]