Please disable your adblock and script blockers to view this page
 

C++ Language program to calculate factorial of a number using for loop

In this article i will explain How to write/create a program to find/get/calculate factorial of entered number using For loop in C++ language.

Description:  To calculate factorial of number, simply multiply  from 1 to that number or that number to 1 i.e. the factorial of a number 'n' is the product of all number from 1 up to the number 'n' or from 'n' up to 1 and it is denoted by n!.

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

  For example 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 C++ program to calculate Factorial of a number.

#include<conio.h>
#include<iostream.h>
int main()
{
    clrscr();
  unsigned long long int  fact=1;
  int i,n;
  cout<<"Enter any positive number to calculate its factorial: ";
  cin>>n;
  for(i=n;i>=1;i--)
  {
    fact=fact*i;
  }
  cout<<"\nFactorial of " <<n<<" = "<<fact;
  getch();
  return 0;
} 

Note:  We can also use 
for(i=1;i<=n;i++)
  {
    fact=fact*i;
  }  
instead of 
for(i=n;i>=1;i--)
  {
    fact=fact*i;
  }  
in the above program to calculate the factorial of a number.

  • Run the program using Ctrl+F9
 Output:

 Enter any positive number to calculate its factorial: 5
  Factorial of 5 = 120

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon