C++中的循環語句


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM