Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ for Loop

C++ for Loop

C++ Loops C++ Loops

for The loop allows you to write a repeat control structure that executes a specific number of times.

Syntax

In C++ for The syntax of the do...while loop:


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

The following is the control flow of a for loop:

  1. init is executed first and only once. This step allows you to declare and initialize any loop control variables. You may also write no statement here, as long as a semicolon appears.
  2. Next, the conditionis evaluated. If true, the loop body executes. If false, the loop body is not executed and control flow jumps to the statement immediately following the for loop.
  3. After executing the for loop body, control flow jumps back to the above increment statement. This statement allows you to update the loop control variable. This statement can be left empty, as long as a semicolon appears after the condition.
  4. The condition is evaluated again. If true, the loop executes; this process repeats (loop body, then increment step, then re-evaluate condition). The for loop terminates when the condition becomes false.

Flowchart

Example

Example

#include

<
iostream
using
namespace
std

;

int

main

(

)

{

// for loop execution

for

(

int

a

=

10

;

a

<

20

;

a

=

a

1

)

{

cout

<<

"

Value of a:

"

<<

a

<<

endl

;

}

return

0

;

}

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


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

Range-based for Loop (C++11)

The for statement allows simple range iteration:

int

my_array

[

5

]

=

{

1

,

2

,

3

,

4

,

5

}

;

// Multiply each array element by 2

for

(

int

&

x

:

my_array

)

{

x

*=

2

;

cout

<<

x

<<

endl

;

}

// auto type is also from the C++11 new standard, used to automatically deduce the variable's type

for

(

auto

&

x

:

my_array

)

{

x

*=

2

;

cout

<<

x

<<

endl

;

}

The first part of the for statement above defines the variable used for range iteration, just like a variable declared in a normal for loop, and its scope is limited to the loop range. The second block after the ':' represents the range to be iterated.

Example

#include

<
iostream
#include
<
string
#include
<
cctype
using
namespace
std

;

int

main

(

)

{

string

str

(

"

some string

"

)

;

// range for statement

for

(

auto

&

c

:

str

)

{

c

=

toupper

(

c

)

;

}

cout

<<

str

<<

endl

;

return

0

;

}

The program above uses a range-based for statement to traverse a string and convert all characters to uppercase, then outputs the result:


SOME STRING

C++ Loops C++ Loops