循环

一 while 循环

int main()
{
    int i = 0,sum = 0;
    while (i<101)
        {
            sum += i;
            i++;
        }
    printf("sum = %d",sum);
    return 0;
}

  输出:

sum = 5050
Process returned 0 (0x0)   execution time : 0.265 s

 

  

int main()
{
    int i = 0;
    while (i<101)
        {
            if(i == 10)
            {
                exit(0); //正常退出
            }
            printf("i = %d\n",i);
            i++;
        }

    return 0;
}

  输出:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9

Process returned 0 (0x0)   execution time : 0.108 s

 

二 do-while

  格式:

#include <stdio.h>
#include <stdlib.h>
int main()
{do{
        代码
    }
    while(条件);
}

  示例:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i = 0;
    do{
        i++;
        printf("%d\n",i);
    }
    while(i<5);
}

  输出:

1
2
3
4
5

Process returned 0 (0x0)   execution time : 0.119 s

 

三 for循环

  格式:

int main()
{
    for (表达式1;表达式2;表达式3)
    {
       语句;
    }
    
}

  注意:

    表达式1,表达式2,表达式3,均可省略,但是两个分号,绝不能省略。

  示例1 :

int main()
{
    int i;
    const int N = 6;
    double total_salary = 0.0;
    double single_salary;
    for (i = 0;i < N;i++)
    {
        printf("input %d months salarys:",i+1);
        scanf("%lf",&single_salary);
        total_salary += single_salary;
    }
    printf("totol_salary:%lf",total_salary);

}

   

  示例2:

int main()
{
    int age;
    for (;;)
    {
        printf("input age:");
        scanf("%d",&age);
        if (age<0)
        {
            printf("age must > 0");
            break;
        }
    }
}

  输出:

input age:5
input age:5
input age:1
input age:-5
age must > 0
Process returned 0 (0x0)   execution time : 9.275 s

 

四  continue 与 break  的区别

  1 使用场合

    continue只能用于循环结构中

    break可以用于循环结构和switch中

  2 作用

    break 跳出循环体

    continue 跳过本次循环,执行下次循环

 

五  实战

int main()
{
    int i = 0;
    int j;
    for (;i<6;i++)
    {
        for(j=0;j<=i;j++)
        {
            printf("%c",'*');  
        }
        printf("\n");
    }


  注意:单引号与双引号的区别!!!!!!!!!!!!!!!!

  输出:

*
**
***
****
*****
******

Process returned 0 (0x0)   execution time : 0.051 s

 

posted @ 2018-06-29 23:16  骑者赶路  阅读(84)  评论(0编辑  收藏  举报