1. Member Join Date
Jan 2017
Posts
1
Rep Power
0

## Where´s the logic?

Good day, everyone. I am learning Java and one lesson I was working on is about calculating a factorial using recursion. The following is the code for it.

public class Application {
public static void main(String[] args) {
int value;
// e.g. 4! = 4*3*2*1 (factorial 4)
System.out.println(factorial(4));
}

private static int factorial(int value) {

if(value == 1) {
return 1;
}

return factorial(value-1) * value;
}
}

My question is where in the code is 4 being multiplied by 3 and then by 2 etc? I think I understand how 4 is getting mulitplied by 3, but then I can´t follow the rest of the logic. Can someone please explain it to me?

Thanks!  Reply With Quote

2. ## Re: Where´s the logic?

where in the code is 4 being multiplied by 3 and then by 2 etc?
Where is the * operator used in the code? That will be where the values are multiplied.
Add some print statements to print out the values used with the * operator.

[code]
[/code]

to get highlighting and preserve formatting.  Reply With Quote

3. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
13

## Re: Where´s the logic?

You should use pencil and paper to record the values and go thru it to see how it works. Here are some simpler examples to start with. The important thing to remember is that values are saved on the stack as each recursive call is made. Also note the only difference of the two methods is the location of the print statement.

Java Code:
```public class RecursionDemo {
public static void main(String[] args) {
printAscending(6);
System.out.println("---------");
printDescending(6);

}

// print values from 1 thru n inclusive
public static void printAscending(int n) {
if (n > 1) {
printAscending(n-1);
}
System.out.println(n);
}

// print values from n thru 1 inclusive
public static void printDescending(int n) {
System.out.println(n);
if (n > 1) {
printDescending(n-1);
}
}
}```
Regards,
Jim  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•