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;
		}
	}

Recommended Answers

All 2 Replies

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

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);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.