Programs

C++ Program to Find Factorial

C++ Program to Find Factorial

Here’s a Turbo C++ program to find the factorial of a given number:

#include <iostream.h>
#include <conio.h>

void main() {
    clrscr();  // Clear the screen (specific to Turbo C++)

    int n;
    long long factorial = 1;  // Using long long to store large results

    cout << "Enter a positive integer: ";
    cin >> n;

    // Check if the number is negative
    if (n < 0) {
        cout << "Factorial is not defined for negative numbers." << endl;
    } else {
        // Calculate the factorial
        for (int i = 1; i <= n; ++i) {
            factorial *= i;
        }
        cout << "The factorial of " << n << " is " << factorial << endl;
    }

    getch();  // Wait for user input (specific to Turbo C++)
}

To compile and run this program in Turbo C++:

  1. Open Turbo C++.
  2. Create a new file and copy-paste the above code into it.
  3. Save the file.
  4. Compile the code (usually by pressing Alt + F9).
  5. Run the program (usually by pressing Ctrl + F9).

After entering a positive integer, the program will display its factorial. If the entered number is negative, the program will notify that factorial is not defined for negative numbers.