intmain() { int i = 1; for (i = 1; i<=10; i++) //第一个表达式是初始化,第二个表达式是判断部分,第三个是调整部分 //不论循环多少次,初始化只有一次 { printf("%d ", i) } return0; }
案例
break
continue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//输出1~4,6~10的整数 intmain() { int i = 1; for (i = 1; i<=10; i++) //第一个表达式是初始化,第二个表达式是判断部分,第三个是调整部分 //不论循环多少次,初始化只有一次 { if (i == 5) { continue; } printf("%d ", i); } return0; }
建议:
不可在for循环体内修改循环变量,防止for循环失去控制
建议for语句的循环控制变量的取值采用“左闭右开区间”
变种
1 2 3 4 5 6 7 8
intmain() { for (;;) { printf("傻逼\n"); } return0; }
判断部分不能省,不然会变成死循环
1 2 3 4 5 6 7 8 9 10 11 12 13
intmain() { int i = 0; int j = 0; for (; i<3; i++) { for (; j < 3; j++) { printf("SB\n") } } return0; }
会输出3个SB
1 2 3 4 5 6 7 8 9 10 11 12
//经典面试题 intmain() { int i = 0; int k = 0; for (i = 0, k = 0; k = 0; i++, k++) { k++; } return0; }
循环0次,因为表达式2不是判断式而是赋值k=0, 也就是k为假,直接就不满足条件跳出去了
do while循环
语法
1 2 3
do 循环语句 while(表达式);
1 2 3 4 5 6 7 8 9 10 11 12 13
//打印1~10 intmain() { int i = 1; do { pringtf("%d\n", i); i++; } while (i<=10);
return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intmain() { int i = 0;
do { if (i == 5) { break; //跳出循环,也就是跳到打印呵呵那里继续执行 } printf("%d\n", i); i++; } while (i <= 10); printf("呵呵"); return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intmain() { int i = 0;
do { if (i == 5) { continue; //跳过后续循环语句,由于i++没执行而且还留在while里会一直死循环 } printf("%d\n", i); i++; } while (i <= 10);
return0; }
案例
1. 计算n的阶乘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//用for循环 intmain() { int i = 0; int n = 0; int fac = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++) { fac = fac * i; } printf("%d\n", fac);
return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//while循环 intmain() { int i = 1; int n = 0; int fac = 1; printf("输入n的数值:"); scanf("%d", &n);
while (i <= n) { //fac = fac * i; fac *= i;//更优雅 i++; }
printf("%d\n", fac); return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//do while循环 intmain() { int i = 1; int n = 0; int fac = 1;
//常规做法 intmain() { int i = 0; int n = 0; int j = 0; int fac = 1; int sum = 0; scanf("%d", &j); for (n = 1; n <= j; n++) { fac = 1;//非常关键,不然不能从1开始往后乘 for (i = 1; i <= n; i++) { fac *= i; } sum += fac; } printf("%d", sum); return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//一个好思路,优化了算法 //相当于重复利用了前面计算的值 intmain() { int i = 0; int n = 0; scanf("%d", &n); int fac = 1; int sum = 0;
for (i = 1; i <= n; i++) { fac *= i; sum += fac; } printf("%d", sum); return0; }
//打印welcome to the world!,但是字符从两端逐渐替换 #define _CRT_SECURE_NO_WARNINGS 1 //放在代码第一行,取消报错显示 #include<stdio.h> #include<string.h> #include<Windows.h>//Sleep的头文件 intmain() { char arr1[] = "welcome to the world!"; char arr2[] = "#####################"; int left = 0; int right = strlen(arr1) - 1;