0

Hi
How can i get a recursive function like this to work:
It should find the sum, then print the sum out inside the function.

public static int myMethod(int counter)
	{
		int sum = 0;
		if(counter == 0)
			return 0;
		else
	    {
		   sum = sum +  myMethod(counter-1);
		   System.out.println("Sum is " + sum);
		   return 0;
		}
	}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by destin
0

I don't understand exactly what your method tries to accomplish but I believe that initializing sum with counter will get you some results, or/and returning the sum instead of zero at the else {...} :

public static int myMethod(int counter)
	{
		//int sum = 0;
		int sum = counter;

                if(counter == 0)
			return 0;
		else
	    {
		   sum = sum +  myMethod(counter-1);
		   System.out.println("Sum is " + sum);
		   
                  //return 0;
                  return sum;
		}
	}

I mean if you look at your return statements you always returned 0. So even if you did: sum = sum + myMethod(counter-1); in the end you returned 0 and sum was initialized to zero. So:
sum = 0 + myMethod() and myMethod returned zero again

0

Keep in mind you aren't looping here, so the sum variable is not doing anything useful.

You can rewrite javaAddict's code to be like this:

public static int myMethod(int counter) {
    if (counter == 0)
        return 0;
    else
        return counter + myMethod(counter - 1);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.