Recursion in Java - Examples with Dry Run
1. Factorial Using Recursion
Java Code:
public class FactorialExample {
static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
public static void main(String[] args) {
[Link]("Factorial of 4 is: " + factorial(4));
Dry Run:
factorial(4)
= 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
= 4 * 3 * 2 * 1 * factorial(0)
= 4 * 3 * 2 * 1 * 1 = 24
Call Stack:
factorial(4)
|-- factorial(3)
|-- factorial(2)
|-- factorial(1)
|-- factorial(0) -> 1
<- return 1
<- return 2
<- return 6
<- return 24
Output:
Factorial of 4 is: 24
2. HCF Using Recursion
Java Code:
public class HCFExample {
static int hcf(int a, int b) {
if (b == 0)
return a;
else
return hcf(b, a % b);
public static void main(String[] args) {
int a = 48, b = 18;
[Link]("HCF of " + a + " and " + b + " is: " + hcf(a, b));
Dry Run for hcf(48, 18):
Step 1: hcf(48, 18) -> hcf(18, 12)
Step 2: hcf(18, 12) -> hcf(12, 6)
Step 3: hcf(12, 6) -> hcf(6, 0)
Step 4: hcf(6, 0) -> returns 6
Call Stack:
hcf(48, 18)
|-- hcf(18, 12)
|-- hcf(12, 6)
|-- hcf(6, 0) -> 6
<- return 6
<- return 6
<- return 6
Output:
HCF of 48 and 18 is: 6