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:
Sorting and searching algorithms: Quicksort and mergesort are examples of sorting algorithms that make use of recursion.
Tree and graph traversals: Algorithms to traverse or search data structures like trees and graphs, such as depthfirst search or breadthfirst search, are often implemented recursively.
Problemsolving: 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:
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 subproblems.
Less Code: Recursive solutions often require less code than iterative solutions.
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:
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.
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.
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
Generally the recursion function will quit based on the condition stated in the function or using a break statement or a return functionPreethi RamanCan you plzz say me how to stop the recursion function 
krishna_540
can u pls tell me the exact problem wher u want to break the function so that i can be more clearPreethi RamanCan you plzz say me how to stop the recursion function 
Ashutosh_shuklaRecursive 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 RamanThanks 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.. 
komputergeekbreak and goto are used to terminate loop.

komputergeek
If you don't specify any statement to terminate,it will form infinite loop.Preethi Ramandoes the recursion function forms
an infinite loop???
e.g
void func() { func(); }

rscrbv
i think u r not knowing correct concept of recursionPreethi RamanCan you plzz say me how to stop the recursion function
Given here in pseudocode:function factorial(n)
{
if (n<=1)
return 1;
else
return n * factorial(n1);
} 
mokshrecursion function have a base condition ....
every time the function is called ... the value moves closer to he base condition.... 
Ahmad SuudiPlease try :
publicstaticvoidMain(string[]args)
{
tampil(10);
}
privatestaticvoidtampil(inti)
{
Console.WriteLine("Halo"+i.ToString());
if(i>0)
tampil(i1);
}
You are reading an archived discussion.