6! "Factorial of six"

Hello guys,

I have a slight difficulty finding the most efficient way to represent 6! "factorial of six", here is my feeble attempt to come up with a code, please hand me some ideas, I'd appreciate it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;


int main()

{
	int i = 1;
	int j = 1 + i++; 
	int k = 1 + i++;
	int l = 1 + i++;
	int n = 1 + i++;
	int m = 1 + i++;
	int q = 1;
	int p = 1 * j*k*l*n*m;
	
	cout << q<<setw(5)<< j<< setw(5)<<k<< setw(5)<< l<< setw(5)<<n<< setw(5)<<setw(5)<<m<<setw(5)<< endl;
	cout << "The factorial 6! is equal to "<< setw(2)<<p << endl;

	system("pause");



    return 0;
}
I would try recursion or a for loop if possible. Hard-coding just seems silly.

If I'm not mistaken, recursion is generally not as efficient as creating a for/while loop. However, it is more readable.

1
2
3
4
5
6
7
8
9
10
11
12
13
int factorial(int q) {
      if (q <= 1) {
           return 1;
      }
      return q * factorial(q - 1);
}


int main() {
     cout << factorial(6);

     return 0;
}


Last edited on
closed account (48T7M4Gy)
Or
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
	int factorial = 1;
	for (int i = 2; i <= 6; i++)
		factorial *= i;

	std::cout << factorial;
}
Thanks a lot indeed!

I'm still not familiar with the "for" operator and it did appear silly to me too done the hard way. I'll start serious reading and tasking to get myself into more efficient coding;

Thanks again!
closed account (48T7M4Gy)
Check this (and other) tutorials out when you have time.
http://www.cplusplus.com/doc/tutorial/control/
@Kemort, -Thank you ! I will!
Topic archived. No new replies allowed.