C语言教程-详解C语言中的for循环

C语言中的for循环用于多次迭代执行语句或程序的一部分。它经常用于遍历数据结构,如数组和链表。
C语言中for循环的语法如下:
for (Expression 1; Expression 2; Expression 3) {
//要执行的代码
}
C语言中for循环的示例
以下是一个打印1的乘法表的简单for循环程序:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d \n", i);
}
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
使用for循环打印给定数字的乘法表的程序:
#include <stdio.h>
int main() {
int i, number;
printf("Enter a number: ");
scanf("%d", &number);
for (i = 1; i <= 10; i++) {
printf("%d \n", (number * i));
}
return 0;
}
输出:
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
循环体
大括号{}用于定义循环的范围。但是,如果循环只包含一条语句,则我们不需要使用大括号。可以有没有循环体的循环。大括号充当块分隔符,即在for循环内部声明的变量仅在该块内有效,而在外部无效。考虑以下示例:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
int i = 20;
printf("%d ", i);
}
return 0;
}
输出:
20 20 20 20 20 20 20 20 20 20
无限循环的for循环
要使for循环无限循环,我们不需要在语法中给出任何表达式。相反,我们需要提供两个分号以验证for循环的语法。这将作为一个无限for循环。
#include <stdio.h>
int main() {
for (;;) {
printf("Welcome to javatpoint");
}
}