How to Stop Recursion Function?

How to Stop Recursion Function?

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

  • krishna_540
    krishna_540
    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
  • krishna_540
    krishna_540
    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
  • Ashutosh_shukla
    Ashutosh_shukla
    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
  • Preethi Raman
    Preethi Raman
    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..
  • komputergeek
    komputergeek
    break and goto are used to terminate loop.
  • komputergeek
    komputergeek
    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();
    }
  • rscrbv
    rscrbv
    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);
    }​
  • moksh
    moksh
    recursion function have a base condition ....

    every time the function is called ... the value moves closer to he base condition....
  • Ahmad Suudi
    Ahmad Suudi
    Please try :

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

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

    if(i>0)
    tampil(i-1);
    }

You are reading an archived discussion.

Related Posts

Hi,​ ​Check out www FavorGoods com for awesome name brand Shoes,Handbags,Hats,Hoodies,Jeans,Lacoste Shoes, Shorts,Sunglasses,Boots,T-Shirts, watches, clothes,Belts,Boots,Jackets, Jerseys,Jewelry, Suit,Wallets,and more! low prices. Website: www.FavorGoods.com​
Evening all, Im new to the website, I found it through google so i thought id drop a few questions in the hope that some of you clever people will...
I'm disappointed. I look at your response to our Small Talks with people associated with engineering who have changed the world. Not a single comment/appreciation/feedback on our Small Talk with...
Can atmospheric pressure can be greater than 760 mmHg at sea level or it is always less than 760 mmHg.
*water from tank on third floor of building flows down to tap on ground level from a pipe. *when a valve is in first floor to control the flow of...