Que: Write a program to calculate Factorial using recursion in UDF.
A function that calls itself is known as a recursive function. And, this technique is known as recursion.
How recursion works?
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.
Code:
#include <stdio.h>
long int dofactorial(int n);int main()
{
int n;
printf("\mEnter a positive integer: ");
scanf("%d", &n);
printf("\nFactorial of %d = %ld \n", n, dofactorial(n));
return 0;
}
long int dofactorial(int n)
{
if (n >= 1)
return n*dofactorial(n-1);
else
return 1;
}
Output:
No comments:
Post a Comment