← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 5 of 10

Java में Recursion

Recursion तब है जब एक method खुद को एक छोटे टुकड़े पर call करके एक बड़ी problem solve करता है, छोटी dolls रखने वाली nesting dolls जैसा। यह तब रुकता है जब यह सबसे छोटी doll तक पहुंचे।
Syntax
java
static returnType methodName(dataType n) {
    if (baseCondition) {
        return baseValue;
    }
    return methodName(smallerN);
}

Introduction to Recursion

Recursion तब है जब एक method खुद को call करके एक problem को उसी problem के छोटे versions में तोड़ता है, एक loop की तरह जो repeat करता है लेकिन एक loop counter के बजाय call stack से driven।

हर recursive method को एक base case चाहिए, नहीं तो यह हमेशा के लिए खुद को call करता रहेगा जब तक JVM एक StackOverflowError throw न करे।

उदाहरण: Introduction to Recursion

java
// Define the class Main
public class Main {
	static void countDown(int n) {
		// Check whether n == 0
		if (n == 0) {
			// Print a line to the console
			System.out.println("Done");
			return;
		}
		// Print a line to the console
		System.out.println(n);
		countDown(n - 1);
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		countDown(3);
	}
}

Base Case and Recursive Case

Base case problem का सबसे simple version है, वह point जहां method खुद को call करना बंद कर देता है और सीधे एक value return करता है।

Recursive case बाकी सब handle करता है: यह काम का एक छोटा टुकड़ा करता है, फिर base case के करीब move होने वाले arguments के साथ method को फिर call करता है।

उदाहरण: Base Case and Recursive Case

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

Fibonacci Series

Fibonacci sequence, जहां हर number इससे पहले वाले दो का sum है, एक classic recursion example है क्योंकि definition naturally recursive है: fib(n) = fib(n-1) + fib(n-2)।

एक naive recursive implementation elegant है लेकिन उन्हीं values को कई बार recompute करता है, यही कारण है कि इसे अक्सर बाद में memoization introduce करने के लिए उपयोग किया जाता है।

उदाहरण: Fibonacci Series

java
// Define the class Main
public class Main {
	static int fib(int n) {
		// Check whether n <= 1
		if (n <= 1) {
			// Send n back to the caller
			return n;
		}
		// Send fib(n - 1) + fib(n - 2) back to the caller
		return fib(n - 1) + fib(n - 2);
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Loop: repeat while the condition holds
		for (int i = 0; i < 6; i++) {
			// Print to the console without a newline
			System.out.print(fib(i) + " ");
		}
	}
}

Recursive Logic Controls

Poorly designed recursion call stack उड़ा सकता है या कभी terminate नहीं होता, इसलिए हमेशा verify करें कि हर recursive call ऐसे arguments pass करती है जो genuinely base case की ओर सिकुड़ते हैं।

हाथ से कुछ calls trace करना (या call tree draw करना) एक recursion को पकड़ने का सबसे तेज़ तरीका है जो असल में converge नहीं हो रहा।

उदाहरण: Recursive Logic Controls

java
public class Main {
	static int sumDown(int n) {
		if (n <= 0) {
			return 0;
		}
		return n + sumDown(n - 1); // n shrinks toward the base case each call
	}
	public static void main(String[] args) {
		System.out.println(sumDown(4));
	}
}

Iteration vs Recursion

किसी भी recursive algorithm को एक explicit stack या accumulator variables उपयोग करके एक loop के रूप में फिर से लिखा जा सकता है, और iteration आमतौर पर तेज़ है और per call एक stack frame बढ़ाने के बजाय constant stack space उपयोग करता है।

Recursion अब भी preferred है जब यह code को नाटकीय रूप से clearer बनाता है, जैसे tree traversal या divide-and-conquer algorithms।

उदाहरण: Iteration vs Recursion

java
// Define the class Main
public class Main {
	static int factorialRecursive(int n) {
		return n == 0 ? 1 : n * factorialRecursive(n - 1);
	}
	static int factorialIterative(int n) {
		// Declare result and set it to 1
		int result = 1;
		// Loop: repeat while the condition holds
		for (int i = 2; i <= n; i++) {
			result *= i;
		}
		// Send result back to the caller
		return result;
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(factorialRecursive(5));
		// Print a line to the console
		System.out.println(factorialIterative(5));
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Base case भूल जाना, जो StackOverflowError का कारण बनता है।
  2. Base case की ओर न बढ़ना, इसलिए recursion कभी खत्म नहीं होता।
  3. बड़े inputs के लिए recursion उपयोग करना जहां एक loop तेज़ और safer होती।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.