Simple factorial function in C++ :D

TriG0rZ's Avatar, Join Date: Oct 2008
Contributor
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;

count<< "Please enter a interger..";
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)
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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?
}
TriG0rZ's Avatar, Join Date: Oct 2008
Contributor
ah yes i can see what you mean xpi0t0.....thanks for the help almost there
yashlodha's Avatar, Join Date: Feb 2011
Newbie Member
Code:
//Aim: to Find Factorial Of a No. Using function
#include<iostream.h>
#include<conio.h>
long int fact(int);
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();
}
long int fact(int m)
{
	int i;
	long int f=1;
	for(i=1;i<=m;i++)
	{
	f=f*i;
	}
	return(f);
}

Last edited by shabbir; 14Feb2011 at 07:32.. Reason: Code blocks
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
And did you feel the need to inform the entire Tour de France team when you finally stopped falling off your bike?