We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Recursion and For Loop

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!

3
Contributors
2
Replies
8 Hours
Discussion Span
7 Months Ago
Last Updated
3
Views
caswimmer2011
Light Poster
32 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

JamesCherrill
... trying to help
Moderator
8,527 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30

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 
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0567 seconds using 2.65MB