Search code examples
c#arraysrecursion

Outputting an array using recursion


I am trying to write the contents of an array using recursion. My code looks like this:

static void Foo(int[] myArray)
{
    int i = 0;
    Console.WriteLine(myArray[i]);

    if (i < myArray.Length)
        return;

    i++;

    Foo(myArray);
}
static void Main(string[] args)
{
    int[] myArray = {4,6,78,9,0};

    Foo(myArray);
}

However, when I execute the application, instead of the expected output:

4
6
78
9
0

It is only printed the first element:

4

I would like to receive advice that will help me find the right solution


Solution

  • That i variable doesn't maintain state between different function calls.

    Rather you would need to pass i as an argument to the function and update it with the recursive call.

    static void Foo(int[] arr, int i) {
        if (i >= arr.Length) return;
    
        Console.WriteLine(arr[i]);
        Foo(arr, i + 1);
    }
    

    Then call in Main:

    Foo(myArray, 0);