Latest web development tutorials

C ++ for loop

C ++ loop C ++ loop

for loop allows you to write a specific number of cycles to perform repetitive control structures.

grammar

In C ++for loop syntax:

for ( init; condition; increment )
{
   statement(s);
}

Here is the control flow for loop:

  1. init is executed first, and only once.This step allows you to declare and initialize any loop control variables. You can also write any statement that is not here, as long as there is a semicolon to appear.
  2. Next, we will judgecondition.If true, the loop body is executed. If false, the loop body is not executed, and the control flow jumps to immediately for the next statement cycle.
  3. After executing the for loop body, control flow jumps back aboveincrement statement.This statement allows you to update the loop control variable. The statement can be left blank, as long as the conditions appear to have a semicolon.
  4. Condition is judged again. If true, then the execution cycle, the process is repeated (loop body, and then increase the step value, then to re-determine the conditions). When the condition becomes false, for loop terminates.

flow chart

C ++ for loop

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // for 循环执行
   for( int a = 10; a < 20; a = a + 1 )
   {
       cout << "a 的值:" << a << endl;
   }
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

C ++ loop C ++ loop