Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading