0%

分支和循环之for循环

文章时效性提示

本文发布于 521 天前,部分信息可能已经改变,请注意甄别。

语法:

1
2
3
4
for(表达式1:表达式2:表达式3)
{
    循环语句;
}

表达式1是 初始化部分,用于 初始化循环变量。
表达式2是 条件判断部分,用于 判断循环时候终止。
表达式3是 调整部分,用于 循环条件的调整

for语句图解

while循环实现i自增到10

1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main() {
    int i = 0;//初始化
    while (i<10) {//判断
        //...
        i++;//调整
    }
    return 0;
}

for循环实现i自增到10

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main()
{
    int i = 0;
    //初始化,判断,调整
    for (i=1; i<=10; i++) {
        printf("%d\n",i);
    }
    return 0;
}

break

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main()
{
    int i = 0;
    //初始化,判断,调整
    for (i=1; i<=10; i++) {
        if(i == 5)
            break;
        printf("%d ",i);//打印的结果是1 2 3 4
        }
    return 0;
}

打印的结果是1 2 3 4,当i==5时,跳出了for循环。

continue

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main()
{
    int i = 0;
    //初始化,判断,调整
    for (i=1; i<=10; i++) {
        if(i == 5)
            continue;//continue 跳过了打印5,又回到了for循环的判断
        printf("%d\n",i);//打印的结果是1 2 3 4 6 7 8 9 10
    }
    return 0;
}

continue 跳过了打印5,又回到了for循环的判断。

不可以在for循环内部改变循环变量,防止for循环失去控制

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main()
{
    int i = 0;
    for (i=0; i<10; i++) {
        if(i = 5)//这里不是判断,是赋值。这里修改了for循环内部的循环变量,导致死循环
            printf("haha\n");
        printf("hehe\n");
    return 0;
    }

建议for语句的循环控制变量的取值采用“前闭后开区间”写法

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main()
{
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    int i = 1;
    for (i=0;i<10;i++)//这里尽量写i<10,而不是i<=9。虽然运行结果一致,但显然前面的写法是有意义的,代表10次打印(循环、元素)
    {
        printf("%d",arr[i]);
    }
    return 0;
}

for (i=0;i<10;i++){...}这里尽量写i < 10,而不是i <= 9。虽然运行结果一致,但显然前面的写法是有意义的,代表10次打印(循环、元素)。

一些for循环的变种

变种一

1
2
3
4
5
6
7
#include <stdio.h>
int main()
{
    for (; ; ) {
        printf("hehe\n");
    }
}

for循环的初始化、调整、判断均可省略。
for循环的判断部分一旦省略,判断结果一直是真,导致死循环。

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main()
{
    int i = 0;
    for (i=0; i<10; i++) {
        int j = 0;
        for (j=0; j<10; j++) {
            printf("hehe\n");//打印的结果是100个hehe
        }
    }
}

上例打印的结果是100个hehe。

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main()
{
    int i = 0;
    int j = 0;
    for (; i<10; i++) {
        for (; j<10; j++) {
            printf("hehe\n");//打印的结果是10个hehe
        }
    }
}

上例打印的结果是10个hehe。

变种二:两个循环变量

1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main()
{
    int x,y;
    for (x=0,y=0; x<2 && y<5; ++x,y++) {
        printf("hehe\n");//用了2个循环变量,打印的结果是两个hehe
    }
    return 0;
}

上例打印的结果是两个hehe。

1
2
3
4
5
6
7
8
int main()
{
  int i = 0;
    int k = 0;
    for (i=0,k=0; k=0; i++,k++)//中间的判断部分k=0是判断,0为假,不进入for循环,循环0次
        k++;
    return 0;
}

由于0代表恒为假,不进入for循环。