jeudi 25 mai 2017

Is there any difference between if and if-else in this snippet [on hold]

I have this function that calculates the factorial of a number.

int fact(n){
    if(n==1)
        return 1;
    return fact(n-1) * n;
}

I can also write

int fact(n){
    if(n==1)           
        return 1;
    else 
        return fact(n-1) * n;
}

Or I can even write it like this

int fact(n){
    return (n==1) ? 1 : fact(n-1) * n 
}

Is there any difference among the three? The code is in Java but these patterns also emerge a lot in programming. Which one is the best pratice?

Aucun commentaire:

Enregistrer un commentaire