学点 C 语言(7): for 循环
for 循环的基本形式:
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i++) {
printf("%d\n", i);
}
getchar();
return 0;
}
步长:
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i += 2) {
printf("%d\n", i);
}
getchar();
return 0;
}
递减:
include <stdio.h>
int main(void)
{
int i;
for (i = 10; i > 0; i--) {
printf("%d\n", i);
}
getchar();
return 0;
}
可用字符:
include <stdio.h>
int main(void)
{
char c;
for (c = 'A'; c <= 'Z'; c++)
printf("%c\n", c);
putchar('\n');
for (c = 'z'; c >= 'a'; c--)
printf("%c\n", c);
getchar();
return 0;
}
可用小数:
include <stdio.h>
int main(void)
{
double f;
for (f = 0.0f; f < 2; f += 0.3) {
printf("%.1f\n", f);
}
getchar();
return 0;
}
携带其他变量:
include <stdio.h>
int main(void)
{
int i, j=0;
for (i = 0; i < 10; i++, j = i*2) {
printf("%d,%d\n", i,j);
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
int i, j=999;
for (i = 0; i < 10; j = i++) {
printf("%d,%d\n", i,j);
}
getchar();
return 0;
}
嵌套:
include <stdio.h>
int main(void)
{
int i,j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf("%2d ", i*j);
}
printf("\n");
}
getchar();
return 0;
}
break:
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d\n", i);
}
getchar();
return 0;
}
continue:
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i++) {
if (i%5 == 0) continue;
printf("%d\n", i);
}
getchar();
return 0;
}
省略:
include <stdio.h>
int main(void)
{
int i=0;
for (; i < 10; i++) {
printf("%d\n", i);
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
int i;
for (i = 0; ; i++) {
if (i > 10) break;
printf("%d\n", i);
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; ) {
i++;
printf("%d\n", i);
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
int num = 0;
for (;;) {
printf("%d\n", num);
num++;
if (num > 10) break;
}
getchar();
return 0;
}
简化布尔判断
include <stdio.h>
int main(void)
{
int i;
for (i = 10; i > 0; i--) printf("%d\n", i); /* 其中的 i > 0 是个布尔判断 */
for (i = 10; i; i--) printf("%d\n", i); /* 因为 i = 0 即为假, 也可省略; 这和上一句一样 */
getchar();
return 0;
}
实例: 输出 0-100 的整数, 10 个一换行
include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 100; i++) {
if((i%10 == 0) && i) putchar('\n');
printf("%2d ", i);
}
getchar();
return 0;
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询