Factorial function with for loop

Here is what I have so far for my part 1 code: It works except it's not calling the main function again in the case I want it to.

Psuedocode:

Prompt user to enter a number to compute the factorials of
Validate number is not 0 or 1
If number is less than or equal to 0 call the main function again
Use count-controlled for loop that accepts only range 1-12
Output the factorial computation

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;
int factorial(int num);
int num;

int main()

{

	int num;
	int product;
	cout << "Enter the number whose factorial has to be calculated. Numbers less than or equal to 0 will recall this main function" << endl;

cin >> num;

product = factorial(num);

	cout << "the factorial from " << num << "is:" << product << endl;

	return 0;

}

//recursive definition of function factorial
int factorial(int num)

{
	int i = 0, product = 1;
{

	if (num <= 0)

{

	//call the main function if num is less than or equal to 0
	int factorial(int num);

}
	else
 
{
	for (i = 1; i <= 8; i++)//count-controlled for loop that accepts only range 1-8
 
{

product = product * i;

}
	return product;
}

}

}
int factorial(int num); line 36
This is a function declaration, NOT a function call.
To call a function, do
factorial(num);

Note that this logic is most likely not correct, the usual recursive implementations of factorial call itself minus 1, so factorial(num - 1) You seem to be trying to erroneously mix iteration with recursion, judging from line 46.
in math: n! == n*(n-1)!

As an aside, you should practice formatted indentation and spacing, it would make it much easier to read. You seem to have extra brackets where you don't need them, and are missing some where you should.
Last edited on
I figured things out, Thanks for the help!!
Topic archived. No new replies allowed.