0

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);
	}
}
4
Contributors
8
Replies
9
Views
6 Years
Discussion Span
Last Post by techyworld
0

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.

0

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.

0

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)

0

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.

0

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

This question has already been answered. 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.