Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find the factorial of a given number

C++ Code Example — Loop Programs

ADVERTISEMENT

WAP to find the factorial of a given number

Objective

Write a C++ program to find the factorial of a given number.

Algorithm / Approach

  1. Read an integer n from the user.
  2. Initialize a res (result) variable to 1.
  3. Start a for loop with i = n and decrement i down to 2 (i--).
  4. Multiply res by i: res = res * i.
  5. Print the result.
main.cpp
include< iostream>
us#ing namespace std;
int main() {
 int n, res = 1;
 cout<<"Enter a number ";
 cin>>n;
 for(int i=n; i>=2;i--) {
  res = res*i;
 }
 cout<<"Result = "<< res<< endl;
return 0;
}

Expected Output

Enter a number 5
Result = 120

Explanation of the Program

  • The factorial of a number N (written as N!) is the product of all positive integers less than or equal to N.
  • We can run the loop backwards (from N down to 2) or forwards (from 1 up to N). Both calculate the exact same mathematical product. Also, note that we initialize res to 1, not 0, because multiplying by 0 would destroy the calculation.

Complexity

Time Complexity O(n) - The loop runs N times.
Space Complexity O(1)
ADVERTISEMENT