How Recursion Is Different From Loop?

 RecursionHere we will learn How Recursion Is Different From Loops? where both are used for executing a set of code multiple times until the condition is true, where recursion is calling a function multiple times until the state is actual, whereas the loop has a set of code that need to execute for a condition.

Although recursion is faster as compared to loop it uses a function call stack to store the call of functions where stacking and unstacking take place at a large scale which results in a lot of memory usage and at times leads to stick overflow for large programs where a function is kept on calling for long times.

Recursion

It is a calling of a function multiple times and executes a set of code time and again until the condition given is true. Moreover, it is a risk when we make a wrong condition and the calling of function continue for infinity. And as it uses the stack for string the function call.

As infinite recursion may lead to the crashing of the system and consuming the whole of the memory, whereas, in the case of a loop, it might not be that much loss.

Let’s understand it with an example.

public class Main {
 public static void main( String[] args) {
 int result = sum(10); 
System.out.println( result); 
} public static int sum( int k) 
{ if (k > 0) {
 return k + sum(k - 1); 
} 
else { 
 return 0; }
 }
 }

 

Here we can see how the function sum is called until k<0, And here we keep on decreasing the value of k each time so one time will come when the value will definitely become less than 0 at that time it will stop executing.

In the same situation, there might be a situation when we increase the value of the variable each time and in that situation, it will run for an infinite time off and that will be a critical situation that might crash the system and consume whole memory.

Loops

Loops are also used for executing a set of codes for a number of time which have complexity as O(n) where the loop is executed for n times and that n the condition which needs to be satisfied.

public class ForExample {  
public static void main( String[] args) {  
    //Code of Java for loop  
    for(int i=1;i<=10;i++){  
        System.out.println( i);  
    }  
}  
}

In the above- given example where a loop is executed 10 times as the condition is given as 10.

 

Learn more about Recursion and loop atLoop Vs Recursion in java

And visit Java Tutorials To learn more about solutions of Java and for learning python follow How Can I Concatenate Two Lists In Python? link.

Leave a Comment

%d bloggers like this: