DEV Community

Neelakandan R
Neelakandan R

Posted on

3 2 3 3 3

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/

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

Top comments (0)

Via QT image

Effortless, secure sharing for even your largest files.

No centralized keys. Post-quantum, end-to-end encryption means no one, not even VIA, can access your data.

To celebrate our launch and Cybersecurity Awareness Month, we’re giving you 1 TB of FREE data transfers when you sign up in October.

See more 🎥

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay