About Lesson
Recursion:
- In C, when a function calls a copy of itself then the process is known as Recursion. To put it Short, when a function calls itself then this technique is known as Recursion.
- While using Recursion, you will have to define an exit condition on that function, if not then it will go into an Infinite Loop.
- Recursion can be used in case of similar subtasks like Sorting, Searching and Traversal Problems.
- You have to be more careful when you are using Recursion in your Program. You just cannot use Recursion in all your Problems because it will make your Program more Complex and Difficult.
- When a function calls itself at least once, the function is called recursive function. While defining a Recursive Function we must take care of these two points:
- Each Time a Function Calls itself it must be closer, in some sense to a solution.
- There must be a Decision criterion for stopping recursive function call otherwise it will execute till the stack overflows.
Example of Recursion:
#include <stdio.h>// Function prototype for factlong fact(int);int main() {int n;long f;printf(“nEnter a value to find factorial: “);scanf(“%d”, &n);f = fact(n);printf(“nFactorial = %ld”, f);return 0;}// Function definition for factlong fact(int n) {if (n <= 1)return 1; // The base case for factorial is typically 1, not nelsereturn n * fact(n – 1);}
Output:
Enter a value to find factorial: 9
Factorial = 362880
Iteration:
- When we use the term Iteration, we’re usually talking about loops. For, While and do…While loops in ‘C‘ are loops that will execute as long as a condition is true.
- Iteration is one of the reasons that Computer Program exist in the First Place.
- You Shouldn’t need to manually Calculate a value a thousand times over.
- Let the Program do the Heavy Lifting, Iteration introduces the risk of an Infinite Loop, in which the Condition is always true and the program will run forever unless Stopped.