Find the Factorial of a Number: C++

Video tutorial to find the factorial of a number: if the user enters 3, then the factorial is 1 * 2 * 3 i.e., factorial = 6
This logic must be handled with a c++ program.

Full Source Code

#include
#include

void main()
{
  int fact = 1, N;
  clrscr();

  cout< >N;

  for( int i=1; i< =N; i++ )
   fact = fact * i;  // OR fact *= i;

  cout<

Here the for loop stars from 1 and not 0. As anything multiplied by 0 would also be zero.


fact *= i; is the compact representation of fact = fact * i;

Video Tutorial: Factorial in cpp



YouTube Link: https://www.youtube.com/watch?v=ovrdIQZ6Hu8 [Watch the Video In Full Screen.]



Output:
Enter a number
5
Factorial of 5 is 120

View Comments

  • my program is just giving factorial for 1 and 2…..why it is giving wrong output for 3 and above numbers?…here is the code
    #include
    using namespace std;
    int main()
    {
    int n,i,j;
    int fact=1;
    cin>>n;
    for(i=1;i>i;
    for(j=1;j<=i;j++)
    {
    fact=fact*j;
    }
    cout<<fact<<endl;
    }
    system ("pause");
    return 0;
    }

  • @domy, There's no need of using two for loops.

    Just follow the coding in our blog post / video and it must work properly.