Recursion और Call Stack
छोटे instance से problem solve करें।
Recursion और Call Stack क्या है?
हर recursive function में base case और उसकी ओर progress चाहिए।
महत्वपूर्ण बातें
- Empty, single, duplicate और sorted input test करें।
- Correctness और optimization अलग रखें।
- Production में standard library को प्राथमिकता दें।
देखें यह कैसे काम करता है
हर कॉल को देखने के लिए अगला चरण दबाएँ। नई कॉल कॉल स्टैक पर जाती हैं, और हर कॉल अपना मान उसे लौटाती है जिसने उसे बुलाया था।
C और C++ code examples
#include <stdio.h>
unsigned long long factorial(unsigned number) {
return number < 2 ? 1 : number * factorial(number - 1);
}
int main(void) {
printf("%llu\n", factorial(6));
}
720
#include <iostream>
constexpr unsigned long long factorial(unsigned number) {
return number < 2 ? 1 : number * factorial(number - 1);
}
int main() {
constexpr auto value = factorial(6);
std::cout << value << '\n';
}
720
C और C++ की तुलना
Factorial O(n) time और O(n) stack लेता है; बड़े inputs validate करके iterative solution सोचें।
Loops, pointers, lengths और buffers स्पष्ट लिखे जाते हैं।
Iterators और algorithms operation को storage से अलग करते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- हर comparison trace करें।
- Duplicates और extreme values test करें।
- Standard library के विरुद्ध benchmark करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Recursive Power Compute a power recursively by halving the exponent. मध्यम
- Flatten Arbitrarily Nested Lists (Recursion) Practice recursion by flattening arbitrarily nested lists while skipping null entries. मध्यम