Table of contents | |
Introduction | |
Understanding the Code | |
Input and Output | |
Conclusion |
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
In this article, we will explain how to find the factorial of a number using C++ programming language. We will provide you with a detailed explanation of the code, including an example with input, code, and output.
The C++ code to find the factorial of a number involves the use of a loop statement. There are two types of loops: for loop and while loop. We will use a for loop to find the factorial of a number.
Here is the code to find the factorial of a number in C++:
#include <iostream>
using namespace std;
int main()
{
int n, fact = 1;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
cout << "Factorial of " << n << " is " << fact;
return 0;
}
Let's break down the code line by line:
Let's see an example of how to use this code to find the factorial of a number.
Example: Suppose we want to find the factorial of 5. We would enter the number 5 as the input to the program.
The output of the program would be:
Enter a number: 5
Factorial of 5 is 120
Explanation: The program prompts the user to enter a number. The user enters 5. The for loop multiplies fact by 1, 2, 3, 4, and 5, and stores the result in fact. The value of fact after the loop is 120. Finally, the program outputs the message "Factorial of 5 is 120" to the console.
In this article, we have explained how to find the factorial of a number using C++ programming language. We provided you with a detailed explanation of the code, including an example with input, code, and output. We hope this article has helped you to understand how to find the factorial of a number using C++. Happy coding!
70 videos|45 docs|15 tests
|
|
Explore Courses for EmSAT Achieve exam
|