Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Monday, 23 March 2015

Introduction: In this article i will explain how to create  a program to find/get/calculate factorial of entered number using For loop in C language.
Factorial:   Mathematically, the formula for the factorial is as follows. If n is an integer greater than or equal to 1, then
n ! = n ( n - 1)( n - 2)( n - 3) ... (3)(2)(1)
Rule: n! = n*(n-1)!

   So 1! = 1
        2! = 2×1 = 2
        3! = 3×2×1 = 6
        4! = 4×3×2×1 = 24
        5! = 5×4×3×2×1 = 120
        6!=  6×5×4×3×2×1 = 720


 or we can say if n=6 then factorial of 6 will be calculated as 1*2*3*4*5*6= 720 or 6*5*4*3*2*1=720.  So 6 != 720.

Implementation: Let's create a program to calculate Factorial of a number.

 #include<conio.h>
#include<stdio.h>
int main()
{
  unsigned long long int fact=1; 
  int i,n;
  clrscr();
  printf("Enter any positive number to calculate its factorial: ");
  scanf("%d",&n);
  for(i=1;i<=n;i++)
  {
    fact=fact*i;
  }
   printf("\nFactorial of %d = %llu",n,fact);
   getch();
   return 0;
}

Note:  We can also use 
  for(i=n;i>=1;i--)
  {
    fact=fact*i;
  }
instead of 
  for(i=1;i<=n;i++)
  {
    fact=fact*i;
  }

Now Run the program using Ctrl+F9
Categories:

0 comments:

Post a Comment