C++ for 循环

for 循环允许您编写一个执行特定次数的循环的重复控制结构。

语法

C++ 中 for 循环的语法:

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

下面是 for 循环的控制流:

流程图

pic001.jpg

实例

实例

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

当上面的代码被编译和执行时,它会产生下列结果:

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

基于范围的for循环(C++11)

for 语句允许简单的范围迭代:

int my_array[5] = {1, 2, 3, 4, 5};
// 每个数组元素乘于 2
for (int &x : my_array) {
    x *= 2;
    cout << x << endl;  
}
// auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
for (auto &x : my_array) {
    x *= 2;
    cout << x << endl;  
}

上面for述句的第一部分定义被用来做范围迭代的变量,就像被声明在一般for循环的变量一样,其作用域仅只于循环的范围。而在":"之后的第二区块,代表将被迭代的范围。

实例

#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std;  
  
int main() {  
    string str("some string");  
    // range for 语句  
    for (auto &c : str) {  
        c = toupper(c);  
    }  
    cout << str << endl;  
    return 0;  
}

上面的程序使用Range for语句遍历一个字符串,并将所有字符全部变为大写,然后输出结果为:

SOME STRING