Find the Factorial of a Number: C++

Advertisement:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream .h>
#include<conio .h>
 
void main()
{
  int fact = 1, N;
  clrscr();
 
  cout< <endl<<"Enter a number\n";
  cin>>N;
 
  for( int i=1; i< =N; i++ )
   fact = fact * i;  // OR fact *= i;
 
  cout<<endl<<endl<<"Factorial of "<<N<<" is "<<fact;
 
  getch();
}

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

factorial-cpp


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

Video Tutorial: Factorial in cpp


You need to a flashplayer enabled browser to view this YouTube video

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



Output:
Enter a number
5
Factorial of 5 is 120

Advertisements

2 thoughts on “Find the Factorial of a Number: C++”

  1. 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;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *