mercredi 9 décembre 2015

C difference between using if or while in recursion

While trying to find different possibilities of writing a recursive factorial function, I noticed that I got confused about the differences of using while or if in the following recursive function. I watched the steps for each option using the gdb debugger, and couldn't see any difference either. I know the functionality of the while loop, and that it works iteratively. But since its body contains a recursive call of the function as a return statement, the current function should be 'left' and a new one should be entered, which will lead to entering a new while loop? It seems to me that in this case it works like a regular if statement? I appreciate any clarification on this.

#include <stdio.h>
#include <stdlib.h>

int recursion(int n)
{
    while(n > 0)
        return n * recursion(n-1);
    return 1;
}

int main(void) 
{
    int n = 5;

    printf("%d\n", recursion(n));       

    return EXIT_SUCCESS;
}

alternative recursive function using if leading to the same result:

int recursion(int n)
{
    if(n > 0)
        return n * recursion(n-1);
    return 1;
}

Aucun commentaire:

Enregistrer un commentaire