0
public class Sample {

    /**
     * @param args
     */
    int array[]= {1,2,3};


    //it is used to display the array in format as 3,2,1,2,1,1

    public void sampleFunction(int size)
    {

        while(size >= 0)
        {
            System.out.println(array[size]);
            sampleFunction(size-1);
        }
        //end while loop

    }
    //end sample function

    // starting main class

    public static void main(String[] args) {
        //creating object Sample

        Sample s = new Sample();

    //Calling sample function for display the array elements

        s.sampleFunction(2);
    }
    //end main class


}
//end sample class
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

7 Answers7

3

Java is pass by value only. You're never updating the value of size inside the while loop, so size will always be greater than 0.

public void sampleFunction(int size) {
    while(size >= 0) {
        System.out.println(array[size]);
        sampleFunction(size-1);
        //this fixes your code...
        size--;
    }
}

Even better, since you're handling a recursive method, just remove the while inside it:

public void sampleFunction(int size) {
    if (size <= 0) return;
    System.out.println(array[size]);
    sampleFunction(size-1);
}

The problem using the while loop is that the value of size never changes. This is how the method is executed:

public void sampleFunction(int size) {
    //removed unnecessary code that doesn't generate problems
    while(size >= 0) {
        sampleFunction(size-1);
    }
}

public void main(String[] args) {
    sampleFunction(0); //it will be infinite like this...
}

Now, when you call sampleFunction(0), this is what will happen:

  1. sampleFunction(0) gets called.
  2. The while loop will check if size (whose value is 0) is greater or equal than 0.
  3. Since it is equal than 0, it will call sampleFunction(-1).
    3.1. sampleFunction(-1) gets called.
    3.2. The while loop will check if size (whose value is -1) is greater or equal than 0.
    3.3. Since the condition is not met, do nothing.
    3.4. Finish sampleFunction(-1) execution.
  4. Return to the while check. size value never changed. Go back to 2 (thus getting the infinite loop).

Hints when defining recursive methods:

  • Always define the base case at the top of the method (if cannot be on top, define it as soon as possible you can in the method).
  • After finishing the design, test it using paper and a pencil (or a pen) and try to follow its execution there (not by executing it in the pc). This will help you check if you missed something. Once you gain more experience, you can trust more in the design and run it (and hope it doesn't get infinite :P).
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

If you want recursion, why not simply:

public void sampleFunction(int size)
{
    if(size >= 0)
    {
        System.out.println(array[size]);
        sampleFunction(size-1);
    }
}
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
  • thanks. i want to know why it not working with while loop . if condition is true then execute the block of statements else exit. – user3536558 Apr 15 '14 at 15:32
0
public void sampleFunction(int size)
{

    while(size >= 0)
    {
    System.out.println(array[size]);
    sampleFunction(size-1);
    }
//end while loop

}

You mix up recursive calls with imperative loop, you should choose one :

public void sampleFunction(int size)
{

    while(size >= 0)
    {
    System.out.println(array[size]);
    size--;
    }
//end while loop

}

or

public void sampleFunction(int size)
{

    System.out.println(array[size]);
    sampleFunction(size-1);
    }
BaptisteL
  • 490
  • 6
  • 15
0

You might want to use if instead of while since for the looping part you are already using recursive algo.

        if(size >= 0)
        {
            System.out.println(array[size]);
            sampleFunction(size-1);
        }

This makes you approach to base condition in every sub recursive call, since in each recursive call size is getting decrementing and in last recursive step, size will be zero which will stop calling itself recursively and you'll get out of you method finally...

user2009750
  • 3,169
  • 5
  • 35
  • 58
  • what do you mean not working with while loop, you simply have to use if condition, this makes you approach to base condition in every sub recursive call, since in each recursive call size is getting decrementing and in last recursive step size will be zero which will stop calling itself recursively and you'll get out of you method finally... – user2009750 Apr 15 '14 at 15:27
0
 public void sampleFunction(int size){
        while(size >= 0)
        {
            sampleFunction(size-1);
        }   
    }

Think slowly and step by step...

  1. size=1

  2. while(1>=0)

  3. size=0

  4. while(0>=0)

  5. size=-1

  6. while(-1>=0)

  7. evaluates false

  8. then it goes right back to step 2 because you never finished your while loop in step 2.

The solution is to change the while to an if. Do you understand why it is looping forever now? You keep setting your size back to 0 in step 3. If you learn how to use your stepping tool in the debugger you would be able to visualize this.

CodeCamper
  • 6,609
  • 6
  • 44
  • 94
0

You can use Recursion, It would be like this for example:

public void sampleFunction(int size)
    {
       //Stop Condition
       if(size = 0)
        {
            System.out.println("END LOOP");
            System.out.println(array[size]);
        }
       else
        {
            System.out.println(array[size]);
            sampleFunction(size-1);
        }
    }
Alaeddine
  • 1,571
  • 2
  • 22
  • 46
0

One thing to keep in mind with recursion is that it creates multiple copies of the parameters and local variables. Suppose your main calls sampleFunction(4). Then sampleFunction(4) calls sampleFunction(3), which calls sampleFunction(2), which calls sampleFunction(1), which calls sampleFunction(0). At that point, there are 5 versions of sampleFunction on the stack, that are all active at the same time; and each one has its own size parameter. Also, if you had a local variable:

public void sampleFunction(int size) {
    int x = size * 100;
    ...
}

each of the 5 versions would also have its own x variable. So the five methods that are now all active look something like this:

sampleFunction(4)   size=4  x=400   calls:
sampleFunction(3)   size=3  x=300   which calls:
sampleFunction(2)   size=2  x=200   which calls:
sampleFunction(1)   size=1  x=100   which calls:
sampleFunction(0)   size=0  x=0

There are now five sizes, and five xs, in your program. This should help you see why if, say, sampleFunction(0) changes size or x, that only affects its own size or x; it doesn't touch any of the others. Also, when sampleFunction(4) calls sampleFunction(3), the effect is that a new size variable (parameter) is created whose value is 3, but this does not affect sampleFunction(4)'s size at all--its value will be 4. And if sampleFunction(4) doesn't do anything to assign to size, its own size will be 4 forever, which is why you're getting an infinite loop.

This applies to variables whose type is a primitive type, like int, and also to variables whose type is a reference to an object. But note that it doesn't apply to objects themselves. If you have a recursive method like:

public void recursiveMethod(MyClass c, int n) {
    ...
    recursiveMethod(c, n-1);
    ...
}

then if there are five recursiveMethod's on the stack, there will be five different c parameters, but they will all refer to the same object, unless one of the recursiveMethod methods reassigns its own c to something else.

ajb
  • 31,309
  • 3
  • 58
  • 84