# Simple factorial function in C++ :D

Discussion in 'C++' started by TriG0rZ, Feb 11, 2009.

1. ### TriG0rZNew Member

Joined:
Oct 2, 2008
Messages:
88
0
Trophy Points:
0
Location:
UK
Basiclly what im trying to to (and not for uni but for someone else) is to try and create a function to take a interger from a user and find the factorial of is.

Factorial being :

The factorial of 2 is:
2x1=2
The factorial of 9 is:
9 x 8x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 720

So far i can do:

int num;

cin<< num;

now i need the funcation to somehow do the factoril bit :P

this being a error trap saying if the answer is <=0 then jsut return 0

if(numfac==>0)
{

cout>>numfac;
else
cout<<0;
}

So if anyone can help in being able to do the function bit that would be amazingly helpfull thanks sexy people

(ignore any mistakes i just that bit on the spot lol)

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
Write a function that calculates the given number multiplied by that number minus one.
Ensure for 1 and less it returns a suitable value.
Make sure it is fully debugged before you go on to the next step and that some test values return the correct result, e.g. 1->1, 3->6, 6->30, 12->132 (remember at this point all it is calculating is n*(n-1).

Then instead of "that number minus one", just call the function from within itself with "that number minus one" as the given number.

Easy!

Code:
```int f(int n)
{
...
// recursive call
int something=someval*f(n-1);
...
return what?
}
```

3. ### TriG0rZNew Member

Joined:
Oct 2, 2008
Messages:
88
0
Trophy Points:
0
Location:
UK
ah yes i can see what you mean xpi0t0.....thanks for the help almost there

4. ### yashlodhaNew Member

Joined:
Feb 14, 2011
Messages:
1
0
Trophy Points:
0
Code:
```//Aim: to Find Factorial Of a No. Using function
[COLOR="Blue"]#include<iostream.h>
#include<conio.h>[/COLOR]
[COLOR="Red"]long int fact(int);[/COLOR]
void main()
{
int n;
long int f=1;
clrscr();
cout<<"\n enetr a value:";
cin>>n;
f=fact(n);
cout<<"\n the factorial is:"<<f;
getch();
}
[COLOR="red"]long int fact(int m)[/COLOR]
{
int i;
long int f=1;
for(i=1;i<=m;i++)
{
f=f*i;
}
return(f);
}```

Last edited by a moderator: Feb 14, 2011

Joined:
Aug 6, 2004
Messages:
3,012