Control Flow

For Loop in C++

The for loop is used to use a control structure that executes a block of code a specified number of times.


Syntax
int controllingVariable;
 
for(initialization; booleanExpression; update) {
    //statements
} //end for loop

Notes

Initialization declares the initial value of the controlling variable. The controlling variable must be declared previously (if using C99 or above, declaration in line is allowed). Typically, the for loop uses an integer variable.

booleanExpression is the controlling statement that must be true in order for the 'for' structure to loop and execute. booleanExpression must result in either a true or false output. It is created using comparing operators (==, >, =, <=, !=). ; There can also be multiple boolean expressions within the parentheses (booleanExpression). The boolean expressions are connected through logical operators (&&, ||, !).

Update is the change in the controlling variable that occurs after each execution of the statements. It performs an arithmetic operation on the controlling variable.


Example
using namespace std;

int x; //controlling variable declaration
for(x = 0; x <10; x++) { 
     cout << x << endl; 
} //x will continue to increment while it remains less than 10.

< Ternary Operator   |   While Loop >

© 2019 SyntaxDB. All Rights Reserved.