当我们需要重复执行一个语句块时,就会使用C / C++中的循环。
For循环是一种重复控制结构,它使我们可以编写执行特定次数的循环。该循环使我们可以在一行中一起执行n个步骤。
句法:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
For循环的各个部分是:
- 初始化表达式:在此表达式中,我们必须将循环计数器初始化为某个值。
例子:int i=1;
- 条件:在此表达式中,我们必须测试条件。如果条件的计算结果为true,那么我们将执行循环的主体并更新表达式。否则,我们将从for循环中退出。
例子:i <= 10
- 更新表达式:执行循环主体后,此表达式将循环变量增加/减少一些值。
例子:i++;
For循环如何执行?
- 控制进入for循环。初始化完成
- 流程跳至条件
- 条件已测试。
- 如果“条件”为真,则流进入身体
- 如果Condition的结果为false,则流程进入循环之外
- 循环体内的语句将被执行。
- 流程进入更新
- 进行更新,流程再次转到步骤3
- for循环已结束,流程已流出。
循环流程图(用于控制流):
示例1:该程序将尝试打印5次“ Hello World”。该程序将以以下方式执行:
C
// C program to illustrate for loop
#include
int main()
{
int i = 0;
// Writing a for loop
// to print Hello World 5 times
for (i = 1; i <= 5; i++) {
printf("Hello World\n");
}
return 0;
}
C++
// C++ program to illustrate for loop
#include
using namespace std;
int main()
{
// Writing a for loop
// to print Hello World 5 times
for (int i = 1; i <= 5; i++) {
cout << "Hello World\n";
}
return 0;
}
C
// C program to illustrate for loop
#include
int main()
{
int i = 0;
// Writing a for loop
// to print odd numbers upto N
for (i = 1; i <= 10; i += 2) {
printf("%d\n", i);
}
return 0;
}
C++
// C++ program to illustrate for loop
#include
using namespace std;
int main()
{
int i = 0;
// Writing a for loop
// to print odd numbers upto N
for (i = 1; i <= 10; i += 2) {
cout << i << "\n";
}
return 0;
}
输出:
Hello World
Hello World
Hello World
Hello World
Hello World
空运行示例1:
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 <= 5 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 <= 5 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 <= 5 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 <= 5 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 <= 5 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 <= 5 yields false.
9. Flow goes outside the loop to return 0
范例2:
C
// C program to illustrate for loop
#include
int main()
{
int i = 0;
// Writing a for loop
// to print odd numbers upto N
for (i = 1; i <= 10; i += 2) {
printf("%d\n", i);
}
return 0;
}
C++
// C++ program to illustrate for loop
#include
using namespace std;
int main()
{
int i = 0;
// Writing a for loop
// to print odd numbers upto N
for (i = 1; i <= 10; i += 2) {
cout << i << "\n";
}
return 0;
}
输出:
1
3
5
7
9
相关文章:
- C和C++中的循环
- C / C++ while循环与示例
- C / C++在示例中执行while循环
- C,C++, Javawhile和do-while循环之间的区别
- C,C++, Java的for和while循环之间的区别
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。