木之夏  
海纳百川,有容乃大;壁立千仞,无欲则刚

C++中的循环语句

while  循环

语法形式

while  (表达式)  语句

{

循环体;

}

程序实例:

求解0-10 的累加之和

 

#include <iostream>
using namespace std;

int main()
{
// while 语句的演示demo
    int num;

    int count;
    int step;
    step = 0;
    count = 0;

    while (step <= 10)
    {
        count += step;
        step++;
    }

    cout << "the sum (from 0 to 10) = " << count <<"\n" ;

    return 0;
}

计算结果:

the sum (from 0 to 10) = 55

do-while 循环

 

 

 

语法形式

do  (表达式)  语句

{

循环体;

}while(判断条件);

程序实例:

求解 0-10 的数字累加

#include <iostream>
using namespace std;

int main()
{
// while 语句的演示demo
    int num;

    int count;
    int step;
    step = 0;
    count = 0;
    
    do{
        count += step;
        step++;
    } while (step <= 10);


    cout << "the sum (from 0 to 10) = " << count <<"\n" ;

    return 0;
}

计算结果:

the sum (from 0 to 10) = 55

 

do-while需要注意的地方:

这个语句会先进行计算do中的循环体,然后再进行结束条件的判断;

for 循环语句

for语句的语法形式;

for(初始语句,表达式1,表达式2)

初始语句:程序先前求解(程序赋初值)

表达式1:为true 时执行循环体(执行条件)

表达式2: 每次执行循环后求解(自增条件)

程序实例:

求解数字0-10的数字之和

 

#include <iostream>
using namespace std;

int main()
{
// while 语句的演示demo
    int num;

    int count;
    count = 0;
    
    for (int step = 0; step <= 10;  step++)
    {
        count += step;
    } 

    cout << "the sum (from 0 to 10) = " << count <<"\n" ;

    return 0;
}

运行结果;

the sum (from 0 to 10) = 55

 

posted on 2021-02-13 10:48  木之夏  阅读(1389)  评论(0编辑  收藏  举报