The Artima Developer Community
Sponsored Link

Java Answers Forum
Recursive method

2 replies on 1 page. Most recent reply: Dec 10, 2002 1:04 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Marie Harris

Posts: 6
Nickname: match
Registered: Nov, 2002

Recursive method Posted: Dec 9, 2002 6:35 PM
Reply to this message Reply
Advertisement
Kindly assist with the question below.

Find the error in the following recursive method and explain how to correct it:

public int sum( int n )
{
if ( n == 0 )
return 0;
else
return n + sum(n);
}


Sonny

Posts: 9
Nickname: proban
Registered: Dec, 2002

Re: Recursive method Posted: Dec 10, 2002 12:01 AM
Reply to this message Reply
Hi Marie Harris,
This looks like a homework. Anyway, the problem in your recursive method is that it never changes the value of n in the later call. So, it will loop forever until stack overflowed --> error.
Look like the method used to sum all numbers from n to 0. So, it can be correct like:

public static int sum(int n )
{
if ( n == 0 )
return 0;
else if (n < 0)
return n + sum(++n);
else
return n + sum(--n);
}

Good luck.

Sonny

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Recursive method Posted: Dec 10, 2002 1:04 PM
Reply to this message Reply
I don't think the first method was actually in error, it just wasn't optimally named. Instead of calling it sum, which is not very descriptive, just rename it to throwStackOverflowError and everything should be fine.

Flat View: This topic has 2 replies on 1 page
Topic: classpath Previous Topic   Next Topic Topic: Hashtable

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use