DEV Community

Debjoty Mitra
Debjoty Mitra

Posted on • Updated on

Head Recursion

When a recursion doesn’t need to do anything in the calling times, it only needs to do things in the returning time, then it is called a head recursion.

void fun(int n){
    if(n>0){
        fun(n-1);
        cout<<n<<endl;
    }
}
Enter fullscreen mode Exit fullscreen mode

Same code using a loop:

void fun(int n){
    int i=1;
    while(i<=n){
        cout<<i<<endl;
        i++;
    }
}
Enter fullscreen mode Exit fullscreen mode

As your can see from here, it is difficult to implement a head recursion using a loop. So, it is better not to write it in loops.

Top comments (0)