介绍
循环(loop)是一系列指令的重复执行,直到达到某个条件或永远执行。for 循环是一种控制流语句,它会重复执行一段代码,直到满足指定的条件。在本实验中,我们将使用 for 循环创建一个简单的程序。
循环(loop)是一系列指令的重复执行,直到达到某个条件或永远执行。for 循环是一种控制流语句,它会重复执行一段代码,直到满足指定的条件。在本实验中,我们将使用 for 循环创建一个简单的程序。
要开始实验,首先你需要启动终端。你可以通过活动选项卡搜索终端,或者在 Ubuntu 中使用快捷键 "Ctrl + Alt + T" 来启动。
现在,在终端中,通过执行以下命令在 ~/project/
目录下创建一个名为 main.c
的新 C 文件:
touch ~/project/main.c
在你喜欢的文本编辑器中打开 main.c
文件。例如,你可以通过运行以下命令使用 nano 编辑器:
nano ~/project/main.c
在文本编辑器中输入以下代码:
#include <stdio.h>
int main()
{
printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
int i = 0;
for(i = 0; i < 10; i++)
{
printf("i = %d\n", i);
}
printf("\n\The value of i after exiting the loop is %d\n\n", i);
printf("\nRemember that the loop condition checks the conditional statement before it loops again.\n\n");
printf("Consequently, when i equals 10, the loop breaks.\n\n");
printf("i is updated before the condition is checked- hence the value of i after exiting the loop is 10 .\n\n");
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
这段代码将使用 for
循环打印从 0 到 9 的数字,并解释循环条件的工作原理。
使用以下命令编译代码:
gcc -o main ~/project/main.c
然后,通过以下命令运行程序:
./main
输出将类似于以下内容:
LabEx - Best place to learn
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
The value of i after exiting the loop is 10
Remember that the loop condition checks the conditional statement before it loops again.
Consequently, when i equals 10, the loop breaks.
i is updated before the condition is checked- hence the value of i after exiting the loop is 10 .
Coding is Fun !
通过调整循环的初始化、条件和更新部分来尝试修改代码。重新运行代码以观察输出的变化。
在这个逐步的实验中,我们学习了如何在 C 语言中创建一个基本的 for
循环程序。现在你应该对如何使用 for
循环、如何定义它们以及如何修改代码以提取不同的输出有了更好的理解。