Recursion

Recursion:

Recursion is a programming and mathematical concept where a function calls itself in order to solve a problem.

Stack: The stack represents a data structure that keeps track of function calls. Each time a function is called, a new stack frame is created to store its local variables and other information. These stack frames are organized in a stack-like manner, and they are popped off the stack as functions return.
Base Case: The base case is a condition within a recursive function that determines when the recursion should stop. It’s the part of the recursion that does not make a recursive call and serves as the termination condition. If the base case is met, the recursion terminates to prevent infinite recursion.

Code:

#include <bits/stdc++.h>
using namespace std;
int i = 0
void hello() {
if (i == 4) {
return; // This is the base case
}
i++;
cout << ""Hello World"" << endl;
hello(); // Recursive call
}
int main() {
hello(); // Initial call to the recursive function
return 0;

Here’s how the code works in terms of the call stack and the base case:
->Initially, i is 0, and the hello function is called from main.
->The function checks the value of i. If it’s equal to 4 (the base case), it immediately returns without making another recursive call.
->If i is not 4, it increments i, prints “”Hello World”” to the console, and makes a recursive call to itself.
->Each recursive call creates a new stack frame on the call stack.
->This process continues until i reaches 4, at which point the base case is met, and the function returns without further recursion.
->As the function calls return, the call stack unwinds, and each stack frame is popped off the stack.