In this example, a for loop is used to determine the factorial of a given number, a. The variable a itself is used as the loop variable. As the value of variable a will be initialized when the scanf statement is executed, the initial expression in the for loop is not required and is omitted.
Note that we have avoided a separate loop variable, reducing the memory requirement of this program. However, the original value of variable a is not available after the loop is executed. This approach is particularly suitable in a function that calculates and returns the value of factorial of a given number.
#include <stdio.h>
#include <conio.h>
void main ()
{
int a;
long f,fact();
clrscr();
printf ("\n Enter a Number : ");
scanf ("%d",&a);
f=fact(a);
printf ("\n The Factorial of %d is : %ld",a,f);
getch();
}
long fact(int b)
{
int i;
long f=1;
for (i=1;i<=b;i++)
f=f*i;
return(f);
}
Output :
Enter a Number : 5
The Factorial of 5 is : 120