Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help c++ program: conditions

  1. Oct 16, 2006 #1
    I need to write a program that prompts me to enter a positive integer N, after doing so it calculates the factorial of that integer and prints it. I am able to do this with the following code.

    #include <iostream>
    using namespace std;
    int main()
    double I, N, Factorial = 1; // Do not forget to initialize Factorial
    cout << "Enter a positive integer:" << endl;
    cin >> N;
    I = 1; // This initialization step has to be done. And it must be done before the while loop.
    while (I <= N) // Notice there is no semicolon here.
    Factorial = Factorial * I; // The body of the loop begins here.
    I = I + 1; // You must increment I. The body of the loop ends here.
    cout << Factorial << endl;
    return 0;

    I now however need to create the condition that IF the integer is greater than 50, I need to apply Stirling's approximation which is = N (NaturalLog(N)) - N. I also need the program to initially check whether or not the integer is positive, and if not to prompt to re-enter.

    Can anyone help??
  2. jcsd
  3. Oct 16, 2006 #2


    User Avatar
    Science Advisor

    The first is just a simple if statement. You'll need to include a math library to get the log. For the second, you should loop until the integer is positive. That is, you input the integer the first time, and then enter a loop so that while the integer is not positive, you tell them so and ask them for it again.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook