--- tags: C++複習講義 --- # 語法複習--while [回目錄](/jHU9MQS5QS-Uvs-ZS6CSxg) ```cpp= while(條件式) { 陳述句一; 陳述句二; } ``` ::: info 例題1: 輸入一整數x,計算 1加到x的和 ::: ```cpp= #include<iostream> using namespace std; int main(){ int sum=0; int x; cin>>x; while(x>=1){ sum+=x; x--; } cout<<sum; return 0; } ``` ## if vs for vs while | if | for | while | | -------- | -------- | -------- | | 判斷完只做一次| 只要符合條件就重複做 | 只要符合條件就重複做| |條件式寫在小括號裡|初質設定、條件式、回合收尾 皆寫在小括號裡|初質設定寫在while前面,條件式寫在小括號裡,回合收尾寫在大括號裡| ```cpp= // 用 while loop 計算n到100有幾個整數 #include<iostream> using namespace std; int main(){ int n; int count=0; cin>>n; //初值設定 while(n<=100){ //條件式 count++; n++; //回合收尾 } cout<<count; //n到100有count個整數 return 0; } ``` ```cpp= // 用 for loop 計算n到100有幾個整數 #include<iostream> using namespace std; int main(){ int n; int count=0; cin>>n; for(int i=n/*初值設定*/ ; i<=100 /* 條件式*/ ; i++ /*回合收尾*/ ){ count++; } cout<<count; //n到100有count個整數 return 0; } ```