How do you write a C program to calculate the factorial within recursive function?

1 answer

Answer

1066955

2026-07-23 20:40

+ Follow

// Iterative solution

unsigned long iterativeFactorial(const unsigned long n) {

unsigned long i, factorial = 1;

for(i = 1; i <= n; i++) {

factorial *= i;

}

return factorial;

}

// Recursive solution

unsigned long recursiveFactorial(const unsigned long n) {

if(n <= 1) {

return n;

}

return n * recursiveFactorial(n - 1);

}

// Sample calls

int main() {

unsigned long n;

printf("Enter a number to find its factorial: ");

scanf("%u",&n);

printf("Iterative factorial: %u\n", iterativeFactorial(n));

printf("Recursive factorial: %u\n", recursiveFactorial(n));

return 0;

}

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.