学习一下 for 循环的几种不同方式,了解一下原理及差异
完整的测试代码参考 GitHub :for 循环测试代码
1 常用形态
对于 for 循环来说,最常用的形态如下
for (表达式1; 表达式2; 表达式3)
{
// code
}
流程图如下:
编写测试代码如下
void forMethod1()
{
cout << "\nThis is i++ test start" << endl;
#if 0
for (int i = 0; i < MAX; i++)
{
cout << "for start i = " << i << endl;
cout << "for test" << endl;
cout << "for end i = " << i << endl;
}
#else
int i; // 循环变量声明放for循环之前,便于查看循环结束后的循环变量值
for (i = 0; i < MAX; i++)
{
cout << "for start i = " << i << endl;
cout << "for test" << endl;
cout << "for end i = " << i << endl;
}
// 此时循环变量已是最后一次修改后的,但不满足循环条件的值
cout << "for exit, i = " << i << endl;
#endif
cout << "This is i++ test end\n" << endl;
}
上述代码执行结果如下
This is i++ test start
for start i = 0
for test
for end i = 0
for start i = 1
for test
for end i = 1
for start i = 2
for test
for end i = 2
for start i = 3
for test
for end i = 3
for start i = 4
for test
for end i = 4
for exit, i = 5
This is i++ test end
从执行结果来看,在退出 for 循环代码块后,i 的值是 5 ,按流程图也就是在经过了最后一次循环变量自增,再去判断循环条件是否满足,此时不满足 i < 5 ,随后退出 for 循环。
2 代码块中修改循环变量
另一种比较常用的方式,就是在代码块中修改循环变量,以实现不同的循环方式。
测试代码如下
void forMethod3()
{
cout << "\nThis is i++ test V2 start" << endl;
int i;
for (i = 0; i < MAX;)
{
cout << "for start i = " << i << endl;
cout << "for test, start i++" << endl;
// 循环体内执行改变循环变量操作,实现不同循环效果
i++;
cout << "for end i = " << i << endl;
}
cout << "for exit, i = " << i << endl;
cout << "This is i++ test V2 end\n" << endl;
}
代码实际运行结果如下文章来源:https://www.toymoban.com/news/detail-852052.html
This is i++ test V2 start
for start i = 0
for test, start i++
for end i = 1
for start i = 1
for test, start i++
for end i = 2
for start i = 2
for test, start i++
for end i = 3
for start i = 3
for test, start i++
for end i = 4
for start i = 4
for test, start i++
for end i = 5
for exit, i = 5
This is i++ test V2 end
此中方式,区别在于将改变循环变量操作放进代码块内执行,以实现不同循环方式,比如文章来源地址https://www.toymoban.com/news/detail-852052.html
// 步长为1
i = i + 1;
i += 1;
i++;
++i;
// 步长为2
i = i + 2;
i += 2;
...
到了这里,关于c/c++普通for循环学习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!