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

Recursion

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

3
Contributors
2
Replies
1 Day
Discussion Span
5 Months Ago
Last Updated
3
Views
london-G
Junior Poster
123 posts since Feb 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

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... :-)

rubberman
Posting Maven
2,571 posts since Mar 2010
Reputation Points: 365
Solved Threads: 305
Skill Endorsements: 51

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?

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
 
© 2013 DaniWeb® LLC
Page rendered in 0.0606 seconds using 2.67MB