CrazyEngineers
  • Sure, in this article, I will explain to you what recursion is and everything you need to know about recursion.

    As a software engineer, you will have to use recursion almost on daily basis while writing code.

    We will also look at a few code examples to understand the concept better.

    What is Recursion?

    Recursion is a programming concept where a function calls itself in its own definition. Essentially, you're breaking down a complex problem into smaller, simpler problems, which are then solved and combined to solve the complex problem.

    Uses and Advantages of Recursion

    Recursion is widely used in solving complex problems where the solution can be applied to smaller parts of the problem. Some specific examples include:

    1. Sorting and searching algorithms: Quicksort and mergesort are examples of sorting algorithms that make use of recursion.

    2. Tree and graph traversals: Algorithms to traverse or search data structures like trees and graphs, such as depth-first search or breadth-first search, are often implemented recursively.

    3. Problem-solving: Many complex problems in domains such as mathematics (e.g., factorial, Fibonacci numbers), artificial intelligence, etc., can be easily solved using recursion.

    The main advantages of recursion are:

    1. Simplicity: Recursive code is generally simpler and easier to read and understand. It reduces the complexity of the problem by breaking it down into smaller, more manageable sub-problems.

    2. Less Code: Recursive solutions often require less code than iterative solutions.

    3. Data Structure Traversal: Recursion is particularly useful when working with certain data structures like trees and graphs, where data is nested or hierarchical.

    Things to Keep in Mind When Using Recursion

    While recursion can be a powerful tool, it's essential to use it carefully, considering the following points:

    1. Base Case: Every recursive function must have at least one base case — a condition under which it stops calling itself and starts returning results back up the call stack. This is crucial to avoid infinite recursion, which can lead to a stack overflow error and crash your program.

    2. Memory Usage: Recursive functions use more memory than iterative ones because each recursive call is added to the call stack, and all local variables and intermediate computations are stored until the function is done executing. Therefore, if the depth of recursion is too high, it could lead to memory exhaustion.

    3. Efficiency: Recursive functions may perform the same calculations multiple times, leading to inefficiency. This can often be mitigated by using techniques such as memoization, where you store and reuse previous results.

    How to Stop a Recursion Function

    The process of stopping a recursion function is generally achieved by defining a condition that determines when the function should stop calling itself — this is known as the base case.

    Here are examples in Python, JavaScript, and Java:

    Recursion in Python

    def count_down(num):
        # Base case: when num reaches 0 or less, stop recursion
        if num <= 0:
            print("Stop!")
            return
        else:
            print(num)
            count_down(num - 1)  # Recursive call
    
    count_down(5)

    In this Python example, count_down is a recursive function that prints numbers starting from a given number down to 1.

    The function stops recursing when the num argument is less than or equal to 0, which is our base case.

    Recursion in JavaScript

    function countDown(num) {
        // Base case: when num is less than or equal to 0, stop recursion
        if (num <= 0) {
            console.log("Stop!");
            return;
        } else {
            console.log(num);
            countDown(num - 1);  // Recursive call
        }
    }
    
    countDown(5);

    In the JavaScript example, countDown is similar to the Python example above, and the logic is the same.

    Recursion in Java

    public class Main {
        public static void countDown(int num) {
            // Base case: when num is less than or equal to 0, stop recursion
            if (num <= 0) {
                System.out.println("Stop!");
                return;
            } else {
                System.out.println(num);
                countDown(num - 1);  // Recursive call
            }
        }
    
        public static void main(String[] args) {
            countDown(5);
        }
    }

    In the Java example, countDown is again similar to the previous examples, demonstrating how the stopping condition or base case of a recursive function works across different programming languages.

    Recursion in PHP

    In PHP, the example will look like this:-

    In this PHP example, countDown is a recursive function that prints numbers starting from a given number down to 1.

    The function stops recursing when the num argument is less than or equal to 0, which is our base case.

    FYI, keep in mind that recursive calls are generally "expensive" operations, as each call adds a new layer to the call stack.

    If your code makes too many recursive calls (either due to a very deep recursion or an infinite recursion), you might run out of memory. This is known as a stack overflow. So, make sure to design your base case properly.

    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • krishna_540

    MemberDec 2, 2008

    Preethi Raman
    Can you plzz say me how to stop the recursion function
    Generally the recursion function will quit based on the condition stated in the function or using a break statement or a return function
    Are you sure? This action cannot be undone.
    Cancel
  • krishna_540

    MemberDec 2, 2008

    Preethi Raman
    Can you plzz say me how to stop the recursion function
    can u pls tell me the exact problem wher u want to break the function so that i can be more clear
    Are you sure? This action cannot be undone.
    Cancel
  • Ashutosh_shukla

    MemberDec 2, 2008

    Recursive functions always contain 2 parts.First that indicates action to be done by this call and second is the one that recursively calls the function again.We may specify condition that is to be satisfied for calling recursively or may also specify the condition of terminating the recursion process.
    For eg: In factorial we continously call until the argument passed is 1 and when argument is 1 we simply return 1 so stop the recursion
    Are you sure? This action cannot be undone.
    Cancel
  • Preethi Raman

    MemberDec 2, 2008

    Thanks a lot for your answer..and also does the recursion function forms
    an infinite loop???
    Its clear that we can terminate the recursive function either by a break,goto,and return functions..
    Are you sure? This action cannot be undone.
    Cancel
  • komputergeek

    MemberDec 3, 2008

    break and goto are used to terminate loop.
    Are you sure? This action cannot be undone.
    Cancel
  • komputergeek

    MemberDec 3, 2008

    Preethi Raman
    does the recursion function forms
    an infinite loop???
    If you don't specify any statement to terminate,it will form infinite loop.

    e.g
    void func()
    {
           func();
    }
    Are you sure? This action cannot be undone.
    Cancel
  • rscrbv

    MemberDec 17, 2008

    Preethi Raman
    Can you plzz say me how to stop the recursion function
    i think u r not knowing correct concept of recursion
    Given here in pseudocode:​
    function factorial(n)
    {
    if (n<=1)
    return 1;
    else
    return n * factorial(n-1);
    }​
    Are you sure? This action cannot be undone.
    Cancel
  • moksh

    MemberDec 19, 2008

    recursion function have a base condition ....

    every time the function is called ... the value moves closer to he base condition....
    Are you sure? This action cannot be undone.
    Cancel
  • Ahmad Suudi

    MemberOct 19, 2014

    Please try :

    publicstaticvoidMain(string[]args)
    {
    tampil(10);
    }

    privatestaticvoidtampil(inti)
    {
    Console.WriteLine("Halo"+i.ToString());

    if(i>0)
    tampil(i-1);
    }
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register