Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Help with factorial

Hi
I try to compile a program where the user can choose between a recursive and a iterative mode of factorial numbers but I didnt succeed, I am a new in c++ please help,
Her is my trying:
/*
#include <iostream.h>
#include <cstdlib>
using namespace std;
//-------------------
//char yours ();
//int read_n();
//int inter();
//int recur() ;
//int factorial(int);
//-------------------
int main()
{
int factorial (int num);
int num;
char yours;
const char inter= 'i';
const char recur= 'r';
cout <<"factorial"<<endl;
cout <<"Program is calculating n!"<<endl;
cout <<"choose a metode!"<< endl;
cout <<"i) iterativ mode"<< endl;
cout <<"r) recursiv mode"<<endl;
cout <<" [i/r]:";
cin>> yours;
int n = read_n();
if (yours == inter){
int result=1;int factorial (int num);
for (int i=1; i<=num; ++i)
result=result*=i;
cout<<" Result of interativ metode: "<<" "<<result<<"! = "<<num <<"." << endl;
}
else if (yours == recur)

{
int factorial (int num)
if (num==1)
return 1;
cout <<" Result of recusiv metode: "<<" "<<n<<"! = "<< factorial(num-1)*num<<"." << endl;
}
return 0;
}
//--------------------
int read_n()
{
int n;
cout <<" n (1 <= n <= 12):";
cin>> n;
if (n < 0||n<=12)
cout << "That is not a positive integer.\n";

return n;
}
//--------------------
//interativ metode
//int inter()
//{
// long sum = 1; int n;
// for (int i=1; i< n+1; i++)
// sum*=i;
// return sum;
//}
//-------------------
//recursiv metode.
//int rekur()
//{

//int factorial(int n); int temp;
//int n;
//if(n <= 1) return 1;

//temp = n * factorial(n - 1);
//return temp;
[2143 byte] By [bello_belli] at [2007-11-11 8:19:00]
# 1 Re: Help with factorial
What is wrong with it? Post the error or explain?

also, just a note, you should "never" (almost never, there might be a good reason to waste all this time looping and recursing) compute a factorial but have a lookup table instead. There are 30 or so in 64-bit math, a few more if you use doubles because the trailing zeros add up and the floating point removes them.
jonnin at 2007-11-11 21:01:26 >
# 2 Re: Help with factorial
there is to many error message and warning when I compile this program, and I dont know how to correct them! :mad:
bello_belli at 2007-11-11 21:02:32 >
# 3 Re: Help with factorial
To start with
1. Use <iostream> instead of <iostream.h>
2. Declare the protypes of functions before defining them.
3. Don't define function inside another function...it's illegal.

Do these changes and come back if you face problem again by posting question in a better way.
Nokia2280 at 2007-11-11 21:03:30 >