Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Simple factorial function in C++ :D (http://www.go4expert.com/forums/simple-factorial-function-cpp-d-t16145/)

TriG0rZ 11Feb2009 16:01

Simple factorial function in C++ :D
 
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 :D

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

xpi0t0s 11Feb2009 18:37

Re: Simple factorial function in C++ :D
 
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 12Feb2009 15:49

Re: Simple factorial function in C++ :D
 
ah yes i can see what you mean xpi0t0.....thanks for the help almost there :D

yashlodha 14Feb2011 07:00

Re: Simple factorial function in C++ :D
 
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);
}


xpi0t0s 14Feb2011 15:45

Re: Simple factorial function in C++ :D
 
And did you feel the need to inform the entire Tour de France team when you finally stopped falling off your bike?


All times are GMT +5.5. The time now is 21:07.