C++ For Loop: Complete Guide with Syntax

The for loop statement in C++ is used to repeatedly execute a specific block of code, it consists of four parts: initialization, condition check, loop body, and iterator. The syntax of the for loop is as follows:

for (初始化表达式; 条件表达式; 迭代器表达式) {
    // 循环体
}

Among them,

  1. Initialization expression: an expression that is executed once before the loop begins, used to initialize a counter or set the loop condition.
  2. Condition expression: an expression that is evaluated before each iteration of a loop, if the condition is true, the loop body is executed; if the condition is false, the loop is exited.
  3. Iterator expression: an expression executed after each loop iteration, used to change the counter or update the loop condition.

The execution process of a for loop is as follows:

  1. Initialize the expression.
  2. Evaluate the conditional expression and if it is true, execute the loop body; otherwise, exit the loop.
  3. Execute the loop body.
  4. Execute the iterator expression.
  5. Go back to step 2, continue evaluating the condition expression, and perform the corresponding operation until the condition expression is false.

The for loop is commonly used to iterate through an array or container, control the number of loops, or implement a specific calculation logic.

bannerAds