English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In programming, loops are used to repeat a specific code block. In this tutorial, you will learn how to create a for loop in C++ programming (with examples).
In programming, loops are used to repeat a specific block until a certain end condition is met. There are three types of loops in C++ 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, then execute the code within the for loop and update the update expression (updateStatement).
Re-evaluate the test expression (testExpression) and then repeat this process until the test expression (testExpression) is false.
// C++ program to find the factorial of a number // n factorial = 1 * 2 * 3 * ... * n #include <iostream> using namespace std; int main() { int i, n, factorial = 1; cout << "Inserisci un numero intero positivo: "; cin >> n; for(i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; {} cout << "Calcolo " << n << "! = " << factorial; return 0; {}
Output the result
Enter a positive integer: 5 Calculate the factorial of 5 = 120
In the program, the user is asked to enter a positive integer, which is stored in the variable n (assuming the user entered 5). This is the workflow of the for loop:
Initially, i equals 1, the test expression is true, and the factorial is 1.
i is updated to 2, the test expression is true, and the factorial becomes 2.
i is updated to 3, the test expression is true, and the factorial becomes 6.
i is updated to 4, the test expression is true, and the factorial becomes 24.
i is updated to 5, the test expression is true, and the factorial becomes 120.
i is updated to 6, the 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 << "Inserisci un numero intero positivo: "; cin >> n; for (int i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; {} cout << "Calcolo " << n << "! = " << factorial; return 0; {}
L'effetto di questo codice è lo stesso dell'effetto del codice sopra