C++ iteration using for loop
Introduction
In this post, we will discuss for loop as it is used often in C++ programs. For loop allows you to execute the action for each iteration in the loop.
Syntax
for(for initialization; for expression ; post expression)
{
// loop statements
}
Loop statements can be a single statement or group of statements nested within curly braces.
Flowchart
Sample program
The following code prompts user to enter a number. It uses a for loop to compute the factorial of the number.
/************************* * C++ for loop demo *************************/ #include <iostream> using namespace std; int main() { int n; int factorial=1; cout << "Please enter a number : " ; cin >> n; // for loop for(int i=2; i<=n; i++) { factorial *= i; } cout << n << " factorial is = " << factorial << endl; return 0; }
run output: Please enter a number : 5 5 factorial is = 120 Process returned 0 (0x0) execution time : 49.577 s Press any key to continue.
For loop is executed until the expression involving the index variable i is false to exit the loop as shown in the flow chart. Any for statement can be converted into a while loop statement in C++.
—
C++ Tutorials
C++ Tutorials on this website:
https://www.testingdocs.com/c-coding-tutorials/
For more information on the current ISO C++ standard
https://isocpp.org/std/the-standard