Problem with the very basics - factorial

Hello dear fellows,
i wrote a little program to calculate the factorial of a natural number but i can't get it to return useful values. The error detection (n < 0)is working fine, but the rest isn't and i don't get why. It runs somehow, but not the right way. In addition, i only want one output instead of two. Please don't be scared by the german output, i bet you can understand it nonetheless :)
Please help.

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
29
30
31
32
#include <iostream>
#include "stdafx.h"
#include "conio.h"

using namespace std;

int fak(int n) {
	if (n == 0 || n == 1) {
		cout << "Die Fakultaet von " << n << " ist 1 .\n";
	}

	else {
		return	n*(fak(n - 1));
		n--;
	}
}


int main(){ 
	int n;
	cout << "Bitte die zu fakultierende Zahl eingeben!\n";
	cin >> n;

	if (n < 0) {
		cout << "Eingabe ist keine natuerliche Zahl!\n";

	}
	else
		cout << "Die Fakultaet von " << n << " ist " << fak(n) << " .\n";
		_getch();
	return 0;
}
Last edited on
Your English is better than my German, but nevertheless the word is "factorial", not "faculty".

If n = 0 or n = 1 it still needs to return a value (1), not just pass comment.

Otherwise it just needs to return n*fak(n-1); no decrementing of n (the n-- line) is necessary.
Try
1
2
3
4
5
int fak(int n)
{
   if (n == 0 || n == 1) return 1;
   else return n*(fak(n - 1));
}



For the future, you might need to try bigger integers (e.g. unsigned long long). Factorials get very big very quickly.
You have been right with the missing return value and the decrementation, now it works perfectly fine. Thanks a lot for the fast answer and the correction in my vocabulary, always appreciated!

The working code if anybody else should search for 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
29
30
31
32
33
34

#include <iostream>
#include "stdafx.h"
#include "conio.h"

using namespace std;

int fak(int n) {
	if (n == 0 || n == 1) {		
		return 1;
	}

	else {
		return	n*(fak(n - 1));		
	}
}


int main(){ 
	int n;
	cout << "Please insert a natural number!\n";
	cin >> n;

	if (n < 0) {
		cout << "Input is not a natural number!\n";

	}
	else
		cout << "The factorial of " << n << " is " << fak(n) << " .\n";
		_getch();
	return 0;
}

Topic archived. No new replies allowed.