Login
Register
All Activity
Questions
Unanswered
Tags
Books
@ProAnswers
Enter your email address:
C Books Guide and List
C++ Books Guide and List
Best Java Books
C program to find factorial of the given number.
+1
vote
C program to find factorial of the given number.
c-program
c
c-language
asked
by
Smita
Advisor
(
7,120
points)
3 Answers
0
votes
Program: To calculate the factorial value using recursion.
#include <stdio.h>
int fact(int n);
int main()
{
int x, i;
printf("Enter a value for x: \n");
scanf("%d", &x);
i = fact(x);
printf("\nFactorial of %d is %d", x, i);
return 0;
}
int fact(int n) {
/* n=0 indicates a terminating condition */
if (n <= 0)
{
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
Explanation:
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
Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters into an infinite loop.
answered
by
sagar
Expert
(
12,340
points)
0
votes
#include<stdio.h>
void main()
{
int n,fact;
int factorial();
printf("enter the no'r whose factorial to be found");
scanf("%d",&n);
fact=factorial(n);
printf("factorial of the no'r=%d",fact);
}
int factorial(int x)
{
int i,f=1;
for(i=1;i<=x;i++)
{
f=f*i;
}
return(f);
}
answered
by
Anusha
Jr Member
(
630
points)
it is the simplest format
0
votes
#include<stdio.h>
main()
{
int a,i;
long int fact;
printf("\n Enter the value of a :");
scanf("%d",&a);
fact=1;
i=1;
while(i<=a)
{
fact=fact*i;
i=i+1;
}
printf("\nFactorial= %d",fact);
}
answered
by
Alokesh Ghosh
Sr Member
(
1,180
points)
Related questions
0
votes
1
answer
C program to check whether the given number is a palindromic number.
asked
by
Smita
Advisor
(
7,120
points)
c-program
c-language
c
+2
votes
3
answers
C program to check whether the given number is even or odd.
asked
by
Smita
Advisor
(
7,120
points)
c-program
c-language
c
+1
vote
2
answers
how to display the multiplication table of a given number using C language?.
asked
by
anonymous
c-program
c-language
c
+1
vote
2
answers
c program to find the maximum of three numbers ?
asked
by
anonymous
c
c-program
c-language
cpp
+2
votes
2
answers
C program to find the greatest of three numbers.
asked
by
Smita
Advisor
(
7,120
points)
c-program
c
c-language