Calculating factorials

Hi everyone

So I was trying out this other exercise where I wrote a program that calculates the factorial of an integer, and so I managed to get that part right:

//File: calculatingfactorials.cpp
#include <iostream>
using namespace std;
int main (void)
{
int K;
int factorial;

factorial = 1;

cout << "Enter an integer: ";
cin >> K;

CHECK:
if (K > 0)
{
factorial = K * factorial;
K = K - 1;
goto CHECK;
}
else
cout << factorial << "\n";
}

I am now supposed to modify the code so that if I enter a number that is not an integer, e.g. -3, it will output that "Factorial cannot be calculated" and I do not know where to even begin the modifications, so any help please.

Kind regards
Matome
Last edited on
Use an if statement. Also -3 is an integer it's just a signed instead of unsigned integer. Do something like:

1
2
3
4
if integer >= 0
     return factorial
else
    return error code
Make a function called factorial. Use if statements to check whether a positive number is given or not. If yes, then use recursion to find the factorial (return n*factorial(n-1);). Otherwise, return -1. In your main code, check the return value. If its positive, print the return value as its the factorial. If its -1, print the error.
This may sound a bit complicated but its not.
I get what you are both saying, but it still doesn't seem to work
What do you mean by it doesn't seem to work? Do you get any errors or something? Can you please post your new code?
Or maybe I just didn't full understand

//File: test.cpp
#include <iostream>
using namespace std;
int main (void)
{
int K;
int factorial;

factorial = 1;

cout << "Enter an integer: ";
cin >> K;

CHECK:
if (K >= 0)
return factorial;

else
return "error code";
}

Please bear with me, this is my first year of ever programming.
You were supposed to fill in the factorial and error code with the factorial/error code :P



there are many ways to get factorials. a simple way would be recursion or you could use a loop. like:
1
2
3
4
5
6
7
[code]int factorial = 1; 
for(int i = 2; i <= n; ++i)
{
    factorial *= n;
}
//factorial of 0 or 1 is 1
//so it's fine that they won't be in the loop 


Then the error code could be return -1; and/or a message like std::cerr << "Error: you can not get the factorial of a negative number." << std::endl;
Ok thanks :-D...it worked
Topic archived. No new replies allowed.