Now, let us understand Head Recursion. Following is the structure of head recursion. If there is a function that is calling itself, then it is a recursive function. As you can see in the below example, the function fun calling itself, so it is a recursive function. Then, if you further notice, the first statement inside the function is the recursive call. That means, what all the processing it has to do, it is doing at returning time, i.e. after the recursive call. There is no statement that is no operation before the function call.
Void fun( int n ) {
fun(n-1); // head recursion
}
}
Void fun( int n ) {
fun(n-1); //call function itself
}
}
Note: The point that you need to remember is if a recursive function does some operation at returning, then it is not easy to convert that recursive function to a loop. We need to convert by writing some logic.
Time Complexity: The time complexity of Head Recursion is O(n).