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!

Recommended Answers

All 2 Replies

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.

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+" "); }

// and call it
// 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 developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.