To study and understand the concept of recursion in C++, and explore how problems can be solved by functions calling themselves until a base condition is reached.
Recursion is a programming technique in which a function calls itself directly or indirectly to solve a problem.
The problem is broken into smaller subproblems of the same type, and the process continues until a base case is satisfied.
- Recursive Function: A function that calls itself.
- Base Case: The terminating condition that stops recursion.
- Recursive Case: The part of the function where it calls itself with a smaller/simpler input.
- Call Stack: Each recursive call is stored in memory; when the base case is reached, the stack unwinds and results are returned.
- Direct Recursion โ Function calls itself directly.
- Indirect Recursion โ Function A calls B, and B calls A.
- Tail Recursion โ Recursive call is the last operation.
- NonโTail Recursion โ Recursive call is followed by extra work.
- Linear Recursion โ Only one recursive call per step.
- Tree Recursion โ Multiple recursive calls per step.
- Start
- Input an integer
n
. - Define recursive function
fact(n)
:- If
n == 0
, return1
(base case). - Else, return
n * fact(n-1)
(recursive case).
- If
- Call
fact(n)
frommain()
. - Display the result.
- End
- Start
- Input an integer
n
. - Define recursive function
sum(n)
:- If
n <= 1
, returnn
(base case). - Else, return
n + sum(n-1)
(recursive case).
- If
- Call
sum(n)
frommain()
. - Display the result.
- End
- Start
- Input a string
str
. - Find the length of the string
n
. - Define recursive function
reverse(str, i, n)
:- If
i == n
, stop (base case). - Else, call
reverse(str, i+1, n)
(recursive case). - After returning, print
str[i]
.
- If
- Call
reverse(str, 0, n)
frommain()
. - Display the reversed string.
- End
Recursion is widely used in mathematics, algorithms, and data structures. Some key applications include:
-
Mathematical Computations
- Factorial, Fibonacci series, power functions, GCD.
-
Searching and Sorting
- Binary Search, Merge Sort, Quick Sort.
-
Data Structures
- Traversal of trees (preorder, inorder, postorder).
- Graph traversal (DFS).
- Linked list operations.
-
Backtracking Problems
- NโQueens problem.
- Sudoku solver.
- Maze pathfinding.
-
String and Array Operations
- Reversing strings.
- Palindrome checking.
- Generating permutations and combinations.
This study of recursion in C++ demonstrates:
- ๐ SelfโReferential Nature โ Functions can call themselves to solve problems.
- ๐ Base Case Importance โ Prevents infinite recursion and stack overflow.
- โป๏ธ Code Simplification โ Complex problems become easier to express.
- โก Applications โ Factorial, sum of numbers, string reversal, sorting, searching, and tree/graph traversal.
๐ Recursion is elegant and powerful, but must be used carefully due to memory and performance considerations.# Recursion.cpp