Factorial Function.

Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N. (Use the for loop).

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main () {
int i, n;
cout << "Enter a number and press ENTER: ";
cin >> n;
for (int i = n; i <= n; i++)
cout << i << " ";

system ("PAUSE");
return 0;
}


How can I change this to do the factorial of 1 to n?
You need to create a function that will compute the factorial. It takes one parameter: N, and it returns the factorial.

Then you need to change the main function to call your factorial function and print out the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <iostream>
using namespace std;

int main () {

int factorial = 1, i;

	cout << "Enter a number and find its factorial: ";
	cin >> i;
	for (int n = 1;  n <= i; n++)
	 factorial=factorial*n;
	cout << factorial << " ";	
	
system ("PAUSE");
return 0;
}


figured it out! :D used online resources
Question, does this test and define the function? o_o
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main () {

int factorial = 1, i, n;

	cout << "Enter a number and find its factorial: ";
	cin >> i;
	for (int n = 1; n <= i; n++)
	factorial = factorial * n;
	cout <<"The factorial for the entered number is: "<<factorial<<endl;	
	
system ("PAUSE");
return 0;
}
Question, does this test and define the function?

No. See the tutorial on functions: http://www.cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.