c语言中的三种循环语句结构

 

001、for

[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c      ## 测试程序,for循环语句
#include <stdio.h>

int main(void)
{
        int i;

        for(i = 1; i <= 5; i++)
        {
                printf("i = %d\n", i);
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk             ## 编译
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
i = 1
i = 2
i = 3
i = 4
i = 5

 

 

002、while

[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c                ## 测试程序
#include <stdio.h>

int main(void)
{
        int i = 6;

        while(i > 0)                     // while循环结构
        {
                printf("i = %d\n", i);
                i--;
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk        ## 编译
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
i = 6
i = 5
i = 4
i = 3
i = 2
i = 1

 

003、do。。。。while

[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c                               ## 测试程序
#include <stdio.h>

int main(void)
{
        int retry;

        do                                                // do while 结构
        {
                int i;
                printf("i = "); scanf("%d", &i);

                if(i % 2)
                {
                        puts("odd!");
                }
                else
                {
                        puts("even!");
                }
                printf("try again, retry = 1; else retry = other integer; retry = ");
                scanf("%d", &retry);
        }
        while(retry == 1);                         // do while结构return 0;
}
[root@PC1 test]# gcc test.c -o kkk                     ## 编译
[root@PC1 test]# ls
kkk  test.c

 。

[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk             ## 测试程序
i = 8
even!
try again, retry = 1; else retry = other integer; retry = 1
i = 325435
odd!
try again, retry = 1; else retry = other integer; retry = 1
i = 34543
odd!
try again, retry = 1; else retry = other integer; retry = 9

 。

 

posted @ 2024-07-27 13:38  小鲨鱼2018  阅读(22)  评论(0编辑  收藏  举报