A function to calculate the factorial value of any integer

#include <iostream>
#include <ctime>
#include <cmath>

//int factoriel (int mynum) {
// int factorial(int mynum);
//int *array = new int[num];
//for (int i = 0; i < num; i++)
// array[i] = i+1;
//int result = std::accumulate(array, array+num, 1, std::multiplies<int>());
//delete [] array;
//return result;
}

int main (){

int myNum;

cout<<"enter the number";
cin >> myNum;

int result = factoriel (myNum);

cout << result;
system ("pause");
return 0;
}
// Program to calculate the factorial of a number with a function
#include <ctime>
#include <iostream>
using namespace std;

// Function Prototype
int Factorial (int M);

int main ()
{
int number=0, result;

// User input must be an integer number between 1 and 10
cout << "Program to calculate the factorial of a number with a function." << endl;

while (number<1 || number>10);
{
cout << "Integer number = ";
cin >> number;
}

// Function call and assignment of return value to result
result = Factorial (number);

cout << "The answer is: " << result << endl;

system ("pause");
return 0;
}

int Factorial (int M)
{
int i, factorial=1;

for (i=1; i<=M; i++)
{
factorial = factorial * i;
}
return factorial;
}


Would i better off wit this code
Last edited on
Can any one tell me what i am doing wrong hear
Not understanding what a factorial is, for a start.

5! = 5*4*3*2*1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<const unsigned N>
struct Factorial
{
    enum V
    {
        val = N * Factorial<N-1>::val
    };
};
template<>
struct Factorial<1>
{
    enum V
    {
        val = 1
    };
};
http://ideone.com/tEb5G

Now, convert it to a function ;)
Last edited on
#include <iostream>
#include <cmath>
using namespace std;


int Factorial (int M);

int main ()
{
int num=1, result;


cout << "Program to calculate the factorial of a number" << endl;

while (num<1 || num>10);
{
cout << "Integer number = ";
cin >> num;
}


result = Factorial (num);

cout << "The answer is: " << result << endl;

system ("pause");
return 0;
}

int Factorial (int M)
{
int i, factorial=1;

for (i=1; i<=M; i++)
{
factorial = factorial * i;
}
return factorial;
}

I got it working this way,thanks anyway.
Topic archived. No new replies allowed.