学点 C 语言(7): for 循环

180it 2020-03-05 AM 2853℃ 0条

学点 C 语言(7): for 循环

  1. for 循环的基本形式:

    include <stdio.h>

int main(void)
{

int i;
for (i = 0; i < 10; i++) {
    printf("%d\n", i);
}
getchar();
return 0;

}

  1. 步长:

    include <stdio.h>

int main(void)
{

int i;
for (i = 0; i < 10; i += 2) {
    printf("%d\n", i);
}
getchar();
return 0;

}

  1. 递减:

    include <stdio.h>

int main(void)
{

int i;
for (i = 10; i > 0; i--) {
    printf("%d\n", i);
}
getchar();
return 0;

}

  1. 可用字符:

    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;

}

  1. 可用小数:

    include <stdio.h>

int main(void)
{

double f;
for (f = 0.0f; f < 2; f += 0.3) {
    printf("%.1f\n", f);
}
getchar();
return 0;

}

  1. 携带其他变量:

    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;

}

  1. 嵌套:

    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;

}

  1. 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;

}

  1. 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;

}

  1. 省略:

    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;

}

  1. 简化布尔判断

    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;

}

  1. 实例: 输出 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;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

学点 C 语言(7): for 循环