by Dinesh Thakur Category: C Programming (Pratical)

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


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.