lundi 11 janvier 2016

How does this recursive function get to this output?

When I run this piece of code for n=5 the output I get is "5 3 1 1 3 5" I get the 5 3 1 part but after that n=-1 but when I run the code with a debugger it when n=-1 it goes to the line after numbers(n-2);i.e System.out.prt(n+ ""); even though that statement is contained in the if block.

Why does this happen?

public void numbers(int n)
{
    if(n>0)
    {
        System.out.print(n+" ");
        numbers(n-2);
        System.out.print(n+" ");
    }
}

TLDR : when n=-1 System.out.prt(n+ "");even though it is within the if block which only runs when n>0.

Any help would be much appreciated. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire