English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Loops are used in programming to repeat a specific code block. In this tutorial, you will learn how to create a for loop in C ++programming creates a for loop (with an example).
Loops are used in programming to repeat a specific block until a certain ending condition is met. C ++There are three types of loops in programming:
for loop
for(initializationStatement; testExpression; updateStatement) { //Code }
Among them, only testExpression is mandatory.
The initialization statement (initializationStatement) is executed only once at the beginning.
Then, evaluate the test expression (testExpression).
If the test expression (testExpression) is false, the for loop terminates. However, if the test expression (testExpression) is true, the code within the for loop is executed, and the update expression (updateStatement) is updated.
Re-evaluate the test expression (testExpression) and then repeat this process until the test expression (testExpression) is false.
// C ++The program finds the factorial of a number // The factorial of n = 1 * 2 * 3 * ... * n #include <iostream> using namespace std; int main() { int i, n, factorial = 1; cout << "Enter a positive integer: "; cin >> n; for(i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout << "Calculate " << n << "! = " << factorial; return 0; }
Output the result
Enter a positive integer: 5 is calculated 5 The factorial of 120
In the program, the user is prompted to enter a positive integer, which is stored in the variable n (assuming the user entered5). This is the working process of the for loop:
Initially, i equals1The test expression is true, and the factorial is1.
i is updated to2The test expression is true, and the factorial becomes2.
i is updated to3The test expression is true, and the factorial becomes6.
i is updated to4The test expression is true, and the factorial becomes24.
i is updated to5The test expression is true, and the factorial becomes120.
i is updated to6The test expression is false, and the for loop terminates.
In the above program, the variable i is not used outside the for loop. In this case, it is best to declare the variable within the for loop (in the initialization statement) as shown below:
#include <iostream> using namespace std; int main() { int n, factorial = 1; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout << "Calculate " << n << "! = " << factorial; return 0; }
This code achieves the same effect as the code above.