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;
}
}
Same code using a loop:
void fun(int n){
int i=1;
while(i<=n){
cout<<i<<endl;
i++;
}
}
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)