1,105,625 Community Members

Recursion

Member Avatar
london-G
Posting Whiz in Training
212 posts since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 1 [?]
 
0
 

Hello,

I am supposed to write recursive program. I have done this below, however I don't know if my understanding of recursion is correct. I believe that it is a method which calls this method inside. In my case (insertCommas).

private String insertCommas(String str)
    {
        if(str.length() < 4){
            return str;
        }
        return insertCommas(str.substring(0, str.length() - 3)) + "," + str.substring(str.length() - 3, str.length());
    }

Is my program recursive?

Thanks

Member Avatar
rubberman
Industrious Poster
4,005 posts since Mar 2010
Reputation Points: 513 [?]
Q&As Helped to Solve: 501 [?]
Skill Endorsements: 87 [?]
 
1
 

The most common type of recursion is what we call "tail recursion" - a function directly calling itself, which is what you are doing here. There is indirect recursion where a function A calls function B, which somewhere down the line agains calls to function A.

So, yes your FUNCTION is recursive. A recursive program is something else entirely... :-)

Member Avatar
Taywin
Posting Maven
2,632 posts since Apr 2010
Reputation Points: 134 [?]
Q&As Helped to Solve: 378 [?]
Skill Endorsements: 17 [?]
 
0
 

As rubberman said, yes it is recursive. If you ask whether it is correct, I would say no. Have you tested it? If a string "1234" goes in, what would be your result? If a string "1234567890123" goes in, what would be your result?

Question Answered as of 9 Months Ago by rubberman and Taywin
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article