*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.

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

**Video Tutorial: Factorial in cpp**

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

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.