2
public class cash
{
    public void test(int a)
    {
        if(a<5)
        {
            System.out.print(a+" ");
            test(++a);
            System.out.println(a);
        }
        System.out.println("fin");
    }
    public static void main(String[] argsc)
    {
        cash c=new cash();       
        c.test(1);
    }
}

The output:

1 2 3 4 fin
5
fin
4
fin
3
fin
2
fin

why ? I think the output should be 1 2 3 4 fin. thank you very much.

3
  • Please improve the post quality using the <code> tag Commented Feb 18, 2012 at 10:26
  • There is no ending clause for recursion. and the fin is always executed. Commented Feb 18, 2012 at 10:29
  • @jurka: There is ending clause: a>=5. The recursion is invoked only if a<5, thus !(a<5) == a>=5 terminates it. Commented Feb 18, 2012 at 11:04

9 Answers 9

4

Ok, so this is your recursive method:

public void test(int a)
{
    if(a<5)
    {
        System.out.print(a+" ");
        test(++a);
        System.out.println(a);
    }
    System.out.println("fin");
}

every statement in this method gets invoked when you call it. lets think about the semantics in this method. This list describes in words, what your method does:

  • check if a<5. if true
    • print out a.
    • call test(++a),
    • print out the incremented a
  • print out "fin"

Your first problem is, that you always (during every invocation of test()) print out "fin". put it in an else {...} block to fix it.

Your second problem is, that you print out the incremented value of a, thats why you get your output. remove the second println-statement (System.out.println(a);) to fix that.

The correct implementation of your method would look like this:

public void test(int a)
{
    if(a<5) {
        System.out.print(a);
        test(++a);
    } else {
        System.out.println("fin");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

public class cash
{
    public void test(int a)
    {
        if(a<5)
        {
            System.out.print(a+" ");
            test(++a);
            return;
        }
        System.out.println("fin");
    }
    public static void main(String[] argsc)
    {
        cash c=new cash();       
        c.test(1);
    }
}

Note: above code has not been tested.

EDIT

Your code didn't have a stop condition after it reached a=5; therefore, the System.out.print line after calling itself recursively was always going to execute as the stack was being popped; hence the output:

1
2
3
4 -- function stops calling itself here and returns. Stack is popped
fin -- Program continues executing the line from the last recursive call (prints fin)
5 --  As above, there were 2 lines pending to execute from the previous call, the system.out.println after test(a++) 
fin  -- And the system.out.println('fin');
4  -- Stack is popped, same 2 lines as above. prints 4 since the value of a when the function was called was 4 then continues on to the next line, which prints 'fin' 
fin
... and so on

4 Comments

thank you ,I just wonder why strange output occurred, whats wrong with that or recursive function works like that? thanks
I would normally write the stop condition first, but this is the simplest change.
@NamoBhagavan I just ran a test in C# and I see that my modification worked. Now that I am sure it works, I'll explain why your code didn't work on my answer.
@NamoBhagavan posted my edit explaining why your recursive function was wrong. I hope my explanation makes sense.
1

This is what your code will execute:

test(1); // Outputs "1", calls test(2), outputs "2" and "fin" after that
test(2); // Outputs "2", calls test(3), outputs "3" and "fin" after that
test(3); // Outputs "3", calls test(4), outputs "4" and "fin" after that
test(4); // Outputs "4", calls test(5), outputs "5" and "fin" after that
test(5); // Outputs "fin" after that

Basically:

"1 " + test(2) + "2" + "fin"
"1" + ("2" + test(3) + "3" + "fin") + "2" + "fin"
"1" + ("2" + ("3" + test(4) + "4" + "fin") + "3" + "fin") + "2" + "fin"
"1" + ("2" + ("3" + ("4" + test(5) + "5" + "fin") + "4" + "fin") + "3" + "fin") + "2" + "fin"
"1" + ("2" + ("3" + ("4" + ("fin") + "5" + "fin") + "4" + "fin") + "3" + "fin") + "2" + "fin"

So your output is correct.

Comments

0

This is where using a debugger would be useful. You would be able to see that as it unwinds the recursion, fin is out put every time, not just when you decide to stop.

Comments

0

The first thing you do in the recursion is print the element, and then recursively call the function.

Let's have a look on the call stack of the recursion. [we will denote each recursive call by its argument a]

At first, you only invoke the method with one element

| |
|1|
---

you will print "1" and invoke recursive call with 2, now the top will be:

|2|
|1|
---

You enter the method again and print the element, 2, and reinvoke with 3, and get:

|3|
|2|
|1|
---

continue this logic, and you will end up printing 1,2,3,4, and get the stack trace:

|5|
|4|
|3|
|2|
|1|
---

Now, the condition does not meet, so you only print fin, and return - results in popping the first element:

|4|
|3|
|2|
|1|
---

when you are back from the recursive call, you print the top+1 [5] and then fin, and again, pop the element from the head of the stack trace, and get:

|3|
|2|
|1|
---

Now again, you print the head+1: 4 and fin, and pop one more element....
Continue this logic until the stack is empty, and you get exactly what the program printed!

Comments

0

During the fourth recursive invocation of your test method the a variable is incremented to 5 before you invoke the method (test(++a)). Since a < 5 is false it will proceed in printing fin and returning (hence your output: 1 2 3 4 fin)

Soon after returns however, it will continue executing the rest of the code which will print 5 followed by fin. The same thing goes on and on for any previous recursive iteration in your code, hence the recursive output: X fin (where X is the value of a in each preceding iteration)

Comments

0

NO!. The o/p is correct...test(++a) will keep calling itself again and again till a=5...once this gets complete, only after that it will print the next line for other values..

test(5)->test(4)->test(3)->test(2)->test(1)

Recursive functions uses stack...so the last in will be first out...

hv a look here.....

Comments

0

Try below code... You will understand How this program is running

public class cash
{
    public void test(int a)
    {
    if(a<5)
    {
        System.out.print(a+" ");
        System.out.print("test 1 - " + a);
        test(++a);
        System.out.print("test 2 - " + a);
        System.out.println(a);
    }
    System.out.println("fin");
    }
    public static void main(String[] argsc)
    {
    cash c=new cash();       
    c.test(1);
    }
}

Update 1

To get what you want, use Below

public class cash
{
    public void test(int a)
    {
    if(a<5)
    {
        System.out.print(a+" ");
//            System.out.print("test 1 - " + a);
        test(++a);
        if (a==5)
        System.exit(0);
//            System.out.print("test 2 - " + a);
        System.out.println(a);
    } else {
    System.out.println("fin");
    }
    }
    public static void main(String[] argsc)
    {
    cash c=new cash();       
    c.test(1);
    }
}

Comments

0

The problem in your solution is that the exit condition of the recursion (a being greater than or equal to 5) is getting executed always. It should be executed only once, the first time the condition holds true - so you must put it in an else block. Also, it's a bad idea assigning to a parameter (the ++a part).

The simplest way I can think of for writing the test method is:

public void test(int a) {
    if (a < 5) {
        System.out.print(a + " ");
        test(a + 1);
    } else {
        System.out.println("fin");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.