DEV Community

Neelakandan R
Neelakandan R

Posted on

1 1 1 1 1

Recursion in Java

Recursion in Java

In Java, Recursion is a process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function.

case Condition in Recursion

In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems.

int fact(int n)
{
    if (n < = 1) // base case
        return 1;
    else    
        return n*fact(n-1);    
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the base case for n < = 1 is defined and the larger value of a number can be solved by converting it to a smaller one till the base case is reached.

Working of Recursion

The idea is to represent a problem in terms of one or more smaller sub-problems and add base conditions that stop the recursion. For example, we compute factorial n if we know the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0

// Factorial using recursion
class GFG {

    // recursive method
    int fact(int n)
    {
        int result;

        if (n == 1)
            return 1;
        result = fact(n - 1) * n;//ex-4 mean 4*3*2*1
        return result;//ex-4 mean ans--24
    }
}

// Driver Class
class Recursion {

    // Main function
    public static void main(String[] args)
    {
        GFG f = new GFG();

        System.out.println("Factorial of 3 is "
                           + f.fact(3));
        System.out.println("Factorial of 4 is "
                           + f.fact(4));
        System.out.println("Factorial of 5 is "
                           + f.fact(5));
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Reference:https://www.geeksforgeeks.org/recursion-in-java/

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay