0% found this document useful (0 votes)
79 views1 page

Factorial of The Given Number

The document discusses calculating factorials recursively. It provides a C program that uses a recursive function called fact to calculate the factorial of a given number. The fact function calls itself, decreasing the parameter n by 1 each time, until reaching the base case of n being 0, at which point it returns 1. This recursive calling is used to multiply the descending numbers together to calculate the factorial. The program then prompts the user for a number, calls the fact function on it, and prints out the factorial result.

Uploaded by

Rajthilak24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views1 page

Factorial of The Given Number

The document discusses calculating factorials recursively. It provides a C program that uses a recursive function called fact to calculate the factorial of a given number. The fact function calls itself, decreasing the parameter n by 1 each time, until reaching the base case of n being 0, at which point it returns 1. This recursive calling is used to multiply the descending numbers together to calculate the factorial. The program then prompts the user for a number, calls the fact function on it, and prints out the factorial result.

Uploaded by

Rajthilak24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

1.

Write a program to find factorial of the given


number.

Recursion: A function is called'recursive 'if a statement within the body of a function calls
the same function. It
is also called'circular definition '. Recursion is thus a process of defining something in
terms of itself.
Program: To calculate the factorial value using recursion.
int fact(int n);
int main(){
int x, i;
printf("En ter a value for x: \n");
scanf("%d" ,&x);
i = fact(x);
printf("\n Factorial of %d is %d", x, i);
return 0;
}int fact(int n){
/* n=0 indicates a terminatin g condition */
if (n
return (1);
}else{
/* function calling itself */
return (n * fact(n - 1));
/*n*fact(n -1) is a recursive expression */
}
}
Output:
Enter a value for x:
4
Factorial of 4 is 24
Explanatio n:
fact(n) = n * fact(n-1)
If n=4
fact(4) = 4 * fact(3) there is a call to fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 * fact(0)
fact(0) = 1
fact(1) = 1 * 1 = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
Thus fact(4) = 4 * 6 = 24
Terminatin g condition( n
infinite loop.

You might also like