📘 Lesson  ·  Lesson 50

Factorial (Recursion)

Factorial (Recursion)

Factorial Program using Recursion in Java

The factorial of n is n × (n-1) × ... × 1. Recursion calls the method on a smaller value each time.

Java Program

static int factorial(int n) {
    if (n == 0) return 1;      // base case
    return n * factorial(n - 1);
}
public static void main(String[] a) {
    System.out.println(factorial(5));   // 120
}

Output

120

How it Works

  • The base case stops recursion at n=0.
  • Each call multiplies n by factorial(n-1) until it reaches the base case.

Summary

  • The factorial of n is n × (n-1) × ... × 1. Recursion calls the method on a smaller value each time.

Factorial Program using Recursion in Java

n का factorial n × (n-1) × ... × 1 है। Recursion हर बार छोटी value पर method call करता है।

Java Program

static int factorial(int n) {
    if (n == 0) return 1;      // base case
    return n * factorial(n - 1);
}
public static void main(String[] a) {
    System.out.println(factorial(5));   // 120
}

Output

120

कैसे काम करता है

  • Base case n=0 पर recursion रोकता है।
  • हर call n को factorial(n-1) से गुणा करती है base case तक।

सारांश

  • n का factorial n × (n-1) × ... × 1 है। Recursion हर बार छोटी value पर method call करता है।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n