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