Source Code
#include <iostream>
using namespace std;
int main()
{
int n; // Declare a variable to hold the number
int fact = 1; // Declare a variable to hold the factorial and initialize it to 1
cout << "Enter a number: "; // Prompt the user to enter the number
cin >> n; // Read the number from the standard input stream
// Calculate the factorial of the number
for (int i = 1; i <= n; i++)
fact *= i;
cout << "The factorial of " << n << " is: " << fact << endl; // Print the factorial
return 0;
}
Code Explanation
This program declares a variable n
of type int
to hold the number entered by the user, and a variable fact
of type int
to hold the factorial of the number. It then uses the cout
object to print a prompt asking the user to enter the number, and the cin
object to read the number from the standard input stream.
To calculate the factorial of the number, the program uses a for
loop to iterate over the range [1, n]
and multiply each number by the factorial. The loop variable i
is initialized to 1, and the loop continues as long as i
is less than or equal to n
. The loop variable is incremented by 1 on each iteration.
Finally, the program uses the cout
object to print the value of fact
, which is the factorial of the number.
What is Loop in C++?
In C++, a loop is a control flow statement that allows you to execute a block of code repeatedly. There are several types of loops in C++, including:
for
loops: These loops execute a block of code a specified number of times. They have a loop variable that is initialized, tested, and updated on each iteration.while
loops: These loops execute a block of code as long as a specified condition is true. The condition is tested at the beginning of each iteration.do-while
loops: These loops are similar towhile
loops, but the condition is tested at the end of each iteration. This means that the block of code will be executed at least once.
Here is an example of a for
loop in C++:
Copy codefor (int i = 1; i <= 10; i++)
{
cout << i << endl;
}
This loop will print the numbers 1 through 10 on separate lines. The loop variable i
is initialized to 1, and the loop continues as long as i
is less than or equal to 10. The loop variable is incremented by 1 on each iteration.
This loop will print the numbers 1 through 10 on separate lines. The loop variable i
is initialized to 1, and the loop continues as long as i
is less than or equal to 10. The loop variable is incremented by 1 on each iteration.
Leave a Reply