C++ function that will compute the factorial of some numbers n using 2 functions

Ok so I am in a intro to c++ class and I have this assignment I have to do:
Write a C++ function that will compute the factorial of some numbers n (input from the user, accept only range 1-8) For each valid number in input, the output should be the value of n!. Your program should use a loop, to allow the user to input more than one number (count-controlled or sentinel-controlled, your choice).Thus, your program should consist of two functions, the main function and the function that calculates factorial sequences.

As you can see below I have a code, but I cant really grasp how to add another function in there, the user should be able to input 2 numbers and right now I can only figure out how to put one..... can anybody direct me to a tutorial!!!???

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

int main ()
{
int factor = 1;
int n;
cout << "Enter in number :\n";
cin >> n;
while (n >1)
{
factor *= n--;
}
cout << "the the sum is " << factor << endl;
return 0;
}
Last edited on
Hi!

Basically, what you'd want in main() is a loop that will take in numbers, test if they're <= 8 and => 1, and if so run your factorial function with n as a parameter (and if n == 0... quit?). That function should probably take an int or something similar, and return... an int. :)

Out of curiosity, do you know how to create functions in C++?
http://cplusplus.com/doc/tutorial/functions/

-Albatross
So what should I add in between?? Im just learning how to create functions and I am so lost. Like For the code above am I missing something in between it to let you add another number.
Ehm... what do you mean by "in between"?

If you mean in your function:
Remember what it's supposed to do: generate factorials. Your main() shouldn't do this.

If you mean in the infinite while loop:
See my first post in this thread. There should be an if statement to check your numbers' validities and run your factorial function if it's right, and another if to catch a number that will tell your while loop to stop repeating itself.

Good luck!

-Albatross
Hello,

thanks for your tutorial, while c++ is very foriegn to me, I didnt understand anything you wrote.

However, I figured it out:

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
#include <iostream>
#include <iomanip>
using namespace std; 

int calculate (int num);

int main()

{
int number; 

cout << "Enter integer number (1-8) = "; 
cin >> number;

while(number>=1 && number<=8) 
{
 int q = calculate(number);
 cout << "Factorial = " << q<< endl; 
 cout << "Enter integer number (1-8) = "; 
 cin >> number;
}

return 0; 
}

int calculate (int num)
{
	int fac=1,k;
	for(int m=1; m<=num; num--) 
      fac = fac * num;
	k = fac;
	return k;
}
Not worth mentioning ,but you can
return fac;
, instead of using an extra variable k.
Last edited on
Topic archived. No new replies allowed.