0

Ok, my problem is a rather weird one. My teacher asked us to write a piece of code that will count how many even numbers are in a given array. my code is as follows:

static void Main(string[] args)
{
    int[] array = { 1, 2, 3, 4, 5, 6 };
    Console.WriteLine(NumOfEvens(array));
}

static int NumOfEvens(int[] array)
{
    return NumOfEvens(array, 0);
}

static int NumOfEvens(int[] array, int index)
{
    if (index == array.Length - 1)
    {
        if (array[index] % 2 == 0)
            return 1;
        else
            return 0;
    }
    if (array[index] % 2 == 0)
        return 1 + NumOfEvens(array, index++);
    else
        return NumOfEvens(array, index++);

}

However, when I ran this, it would output a Stack Overflow. Debugging came to show that the function simply didn't increment my index variable. replacing the increment with a "+1" seemed to fix the issue, but I'm quite curious to learn what might be the cause of this issue.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Delirium
  • 59
  • 1
  • 1
  • 7
  • 2
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator- – Pranav Hosangadi Sep 30 '20 at 15:26
  • 4
    Because you are using the _post increment_ operator. `++index` would have worked, but arguably `index+1` is clearer in it's intent – Matt Burland Sep 30 '20 at 15:26

1 Answers1

2

because if you write ++ at the end than the increment happens after the assignment. it is called "post increment" the old value is passed first and then in is increased:

return NumOfEvens(array, index++);

if you write it at the beginning then the variable will first be incremented and then the value will be passed into the function This is called pre-increment:

return NumOfEvens(array, ++index);

and

return 1 + NumOfEvens(array, ++index);

Documentation

EDIT:

inspired by a comment by Matt Burland who argues that index + 1 is clearer in it's intent since the value of index is actually not used anywhere else and doesn't actually need to increment its current value:

return NumOfEvens(array, index + 1);
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 1
    I'd argue that `index + 1` is clearer in it's intent since you don't actually use the value of `index` anywhere else and don't actually need to increment its current value. – Matt Burland Sep 30 '20 at 16:28
  • @MattBurland i added your suggestion to the answer – Mong Zhu Sep 30 '20 at 16:48