Hey,

I am trying to use a for loop inside a recusive method, but everytime the method runs recursively, the integer in the for loop resets to zero because of the initialization. Is there anyway to keep the integer counting up, and not resetting to zero?

Thanks in advanced!

Re: Recursion and For Loop 80 80

Declare and initialise the integer outside the method (but inside the class). That way each invocation of the method will use the same shared ineteger.

Re: Recursion and For Loop 80 80

Or pass the value which you want to use in the loop inside to the recursive method. That way, the value will be updated every time you call.

// i.e.

public simpleRecursive(int val) {
  if (val>0) {
    for (int i=0; i<val; i++) { System.out.print(i+" "); }
    System.out.println("");
    simpleRecursive(val-1);
  }
}

// and call it
simpleRecursive(4);
// result will be...
// 0 1 2 3 
// 0 1 2 
// 0 1 
// 0 
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.