
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Factorial of a Number Using Iteration in C++
In this article, we'll show you how to write a C++ program to find the factorial of a number using an iterative approach. The factorial of a number is the result of multiplying all the positive integers from 1 to that number. It is written as n! and is commonly used in mathematics and programming.
Let's understand this with a few examples:
//Example 1 Input: 5 The factorial of 5 is: 5 * 4 * 3 * 2 * 1 = 120 Output: 120 //Example 2 Input: 6 The factorial of 6 is: 6 * 5 * 4 * 3 * 2 * 1 = 720 Output: 720
Using Iteration for Finding the Factorial
To find the factorial of a number, we use the iterative method, which means we repeat a task using a loop. In this case, we multiply the numbers from 1 up to the given number to get the factorial.
Here's how we do it:
- First, we initialize the factorial value to 1.
- Then, we run a loop from 1 to the given number(n).
- In each step of the loop, we multiply the current factorial value by the loop number and update it.
- Finally, once the loop finishes, we display the result.
C++ Program to Find Factorial of a Number using Iteration
Here's a C++ program where we calculate the factorial of a given number using an iterative method:
#include <iostream> using namespace std; int main() { int n = 5; //number to calculate the factorial int fa = 1; // Variable to store factorial // for loop for calculation for (int i = 1; i <= n; ++i) { fa *= i; } cout << "Factorial of " << n << " using loop is: " << fa << endl; return 0; }
The output of the above program shows the factorial of 5 calculated using a loop.
Factorial of 5 using loop is: 120
Time Complexity: O(n), because the loop runs n times.
Space Complexity: O(1), we use only a few variables.