Calculating Factorial In C++ Using While Loop






C++ Factorial While Loop Calculator – Full Code Example

\n\n\n\n

\n

C++ Factorial While Loop Calculator

\n

Enter a number and see the factorial calculated using C++ while loop code.

\n\n

\n \n \n

\n\n \n \n\n

\n

\n\n

C++ Factorial While Loop Code Example

\n

Below is the complete C++ program that calculates the factorial of a given number using a while loop.

\n\n

Full Code

\n

\n#include \n\nint main() {\n    int num, fact = 1, i = 1;\n\n    // Input: Get number from user\n    std::cout << \"Enter a number: \";\n    std::cin >> num;\n\n    // Calculate factorial using while loop\n    while (i <= num) {\n        fact *= i;\n        i++;\n    }\n\n    // Output: Display the result\n    std::cout << \"Factorial of \" << num << \" = \" << fact << std::endl;\n\n    return 0;\n}\n    

\n\n

Code Explanation

\n

The program calculates the factorial of a number N, which is the product of all positive integers up to N.

\n\n

Key Components:

\n

    \n

  • int fact = 1;: Initializes factorial to 1 because 0! = 1.
  • \n

  • while (i <= num): The loop continues as long as the counter i is less than or equal to the input number.
  • \n

  • fact *= i;: Multiplies the current factorial by the counter.
  • \n

  • i++;: Increments the counter in each iteration.
  • \n

\n\n

Factorial Results Table

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

Number (N) Factorial (N!) Calculated By

\n\n

\n

💡 Why Use While Loop for Factorial?

\n

The while loop is ideal for factorial calculation because it repeats a block of code as long as a condition is true. In this case, it keeps multiplying numbers until the counter exceeds the input number, making it a simple and efficient method for calculating factorials.

\n

\n\n

\n\n\n\n\n\n