:) My mind went blank for a bit and I couldn't figure out such a simple programme. But then I had a shower and all was well :)

#include <iostream>
#include <string>
#include <cmath>

using namespace std;
int factorial(int i = 1);

int main()
{
	int num = 0;
	bool quit = false;
	while(!quit)
	{
		cout << "Enter number to factorise: ";
		cin >> num;
		num  = (int)fabsf((float)num);	
		if (num > 10)
		{quit = true;}

		cout << factorial(num);
		cout << endl;	
	}
}


int factorial(int i){
	
	int fact = 1;

		for(int j = 1; j < i + 1; j++)
		{
			fact *= j;
		}
	
	return fact;
}

:) My mind went blank for a bit and I couldn't figure out such a simple programme. But then I had a shower and all was well :)

int factorial(int i){

    int fact = 1;

        for(int j = 1; j < i + 1; j++)
        {
            fact *= j;
        }

    return fact;
}

end quote.

You could trim this some more. Try setting fact to the input value i. In fact, since you aren't passing i by reference, you could simply use i to accumulate the factorial. Next start your for loop with j=i-1, decrement j in the loop, and terminate when j<2.

Even though this won't win you much in terms of overall performance, you should still try make your loops as efficient as possible. Eliminate unnecessary iterations and extra variables.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This bit bothers me

if (num > 10)
		{quit = true;}

		cout << factorial(num);

Is it your intent not to find factorial of 10 or greater? And to use the 10 or greater input as a quit signal?

The way you have it, your code will set up to end the main loop on a large input, but will still go ahead and compute factorial of anything, including values for which your int return is too small (13! is too big for int storage.)

How about

if (num > 10)
		{
                    quit = true;
                 }
                 else
                 {
                      cout << factorial(num);
                  }
This article has been dead for over six months. Start a new discussion instead.