Computer Programming C Laboratory: Functions C Programs

C Program to calculate the factorial of an integer number (using recursion)

recursion - C Programming

C Program to calculate the factorial of an integer number.

/* Program to calculate the factorial of an integer number */

#include <stdio.h>

main()

{

int a; /*Local definition */

* Statements /

printf("Enter the number:");

scanf("%d",&a);

printf("The factorial of %d=%d", a, rec(a));

} /* main */

rec(int x)    /* rec() is a function it returns the value to main */

int f;

{

/* Statements */

if(x==1)

     return(1);

else

     f=x*rec(x‒1);

return(f);

} /* rec() */

OUTPUT

Enter the number 5

The factorial of 5=120

EXPLANATION: In the above program the variable a is read through the keyboard. The user defined function. rec() is called from the main function. Here the condition checked x=1, if condition is satisfied, then control transfers to the main program and prints the value. Otherwise else part is executed and calculated the factorial value then it returns the value to the main program. The function rec() is referred as a recursion function.


Computer Programming C Laboratory: Functions C Programs : Tag: C Programming : - C Program to calculate the factorial of an integer number (using recursion)


Computer Programming C Laboratory: Functions C Programs



Under Subject



Related Subjects