Can someone dry run and explain me this code? having problem to understand recursion program.

public class Multiplication {

	public static void main(String[] args)
	{
		System.out.println("Answer:"+Mult(2,3));
	}
	
	public static int Mult(int x,int y)
	{
	
		if (y==1) 
			return x;
		else
			return x + Mult(x,y-1);
	}
}

You will have to learn the concept of a stack first.
It will be a little difficult to explain a concept of a stack, as it is best understood with pictures and graphics !!

Each function call is assigned a new stack frame with memory for its local variables.

Try tracing out the program step by step once you learn the above concept.

I don't think there should be a prob in analyzing the above program(which is wrong though) if you know stack mechanism.

whats wrong in the program?

Did you actually go through stacks ? If so, there is nothing in there for me to point out because it is a very simple mistake. I could point out the mistake to you, you can correct it out and get your program running next minute. But i don't see any purpose learning like that. Learn the concept once, it'll do you a world of good. They are one of the most important concepts.

whats wrong in the program?

Your recursive method works for me (assuming y>=1).

can you explain me this line of code

return x + Mult(x,y-1);

how it works?? how can it add x to the function name Mult(x,y-1)

It calls Mult, passing the values of x and y-1 as parameters. Whatever result is returned from that call is then added to x.

Member Avatar for hfx642

You are not adding x to Mult.
You are adding x to the RESULT of what is RETURNED by Mult.

ok thanks

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.