mardi 1 juin 2021

Need to understand what role played by if condition with return value 0 in calculating the factorial of the function using recursion

#include <stdio.h> int fact(int); int main() { int n, f; printf("Enter the number whose factorial you want to calculate?"); scanf("%d", &n); f = fact(n); printf("factorial = %d", f); } int fact(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return n * fact(n - 1); } }

Above is the solution for finding recursion. My question is if n == 0 then the program is returning 0 and the activation record will the have value 0. If we multiply anything with 0 will get 0 but I am getting the expected result. If I remove the if condition if n == 0 by keeping the n == 1 as if condition still I am getting the result as expected. how this is working?

Aucun commentaire:

Enregistrer un commentaire