-2

how does this loop work that i get the result of 11, 2, 13, 4, 15? What i mean is to explain how one number enters the for loop and what happens

        static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5 };
        fun1(ref arr);

        Console.ReadLine();

    }
    static void fun1 (ref int[] array)
    {
        for (int i = 0; i < array.Length; i = i + 2)
        {
            array[i] = array[i] + 10;
        }
        Console.WriteLine(string.Join(",", array));
    }
}
Eni
  • 9
  • 1
    Use step debugger, step through the code and inspect the variables, this has nothing to do with `ref`, arrays are passed by reference anyway, all you are doing is passing a reference to the reference, which is doing absolutely nothing in this case – TheGeneral Sep 23 '21 at 02:44
  • 2
    `ref` is meaningless here because you're not assigning a new value to `array`. – ProgrammingLlama Sep 23 '21 at 03:06
  • 1
    "arrays are passed by reference anyway" - this is not accurate. By default, a reference to an array is passed by value. It sounds like meaningless semantics, but passing by reference allows a reassignment to the parameter within the function to modify what is assigned to a variable passed in while calling the function. – moreON Sep 23 '21 at 03:41
  • @moreON you got me, I should have said arrays are reference types and references are passed by value, in that cases you are just passing a reference by reference. Though my statement still stands firm – TheGeneral Sep 23 '21 at 03:50

1 Answers1

1

You loop statement

for (int i = 0; i < array.Length; i = i + 2)

Assuming array's length is 5, your loop variable i starts from 0. It them gets incremented by 2 every iteration. This is because you have defined the expression i = i+2. So i go from 0 -> 2 -> 4, when it gets to 6, it doesn't enter the loop.

Thus, you only access the odd elements of the array

edison16029
  • 346
  • 1
  • 9