[Go to site: main page, start]

0% found this document useful (0 votes)
14 views4 pages

Java Recursion Examples and Dry Runs

The document provides examples of recursion in Java, specifically demonstrating how to calculate the factorial of a number and the highest common factor (HCF) using recursive methods. It includes Java code snippets, dry runs, and call stacks for both examples, illustrating the step-by-step execution of the recursive functions. The outputs for the examples are the factorial of 4, which is 24, and the HCF of 48 and 18, which is 6.

Uploaded by

priyanka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Java Recursion Examples and Dry Runs

The document provides examples of recursion in Java, specifically demonstrating how to calculate the factorial of a number and the highest common factor (HCF) using recursive methods. It includes Java code snippets, dry runs, and call stacks for both examples, illustrating the step-by-step execution of the recursive functions. The outputs for the examples are the factorial of 4, which is 24, and the HCF of 48 and 18, which is 6.

Uploaded by

priyanka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like