Recursion Vs Iteration in C programming
Iteration and recursion both are two problem solving technique of solving the iterative problems. The problems which can be solved by performing same calculation many number of times are iterative problems. Among iterative problems, which can be defined in terms of the smaller versions of themselves are recursive problems. Iterative problems can be solved using Iterative programming constructs (or loops). Whereas recursive problems can be solved by using Recursive function.
Iterative programming constructs or loops are the programming tools which are used to execute block of code many number of times repetitively. Recursive functions are the functions which calls themselves from their body with conversing arguments.
Here this program solves the problem of finding factorial by iterative manner.
Iteration Example
int fact(int n){ int f = 1; for(int i = 1; i <= n; i++) { f = f * i; } return f; }
Same problem can be solved by recursion in this way.
Recursion Example
int fact(int n) { if(n <=1) { return 1; } else { return n * fact(n-1); } }
Analysis
Here both of code produce identical result while implementing. But Recursive way to solving is regarded as less efficient due to its memory uses. Values of parameters and return values are stored in stack until the number converges to base value(in this case 1). So Recursive way is less efficient .
Finally
But In recursive way it is easy to code and understand. Generally recursive code is automatically converted to equivalent iterative code in higher level programming language.