--- title: CPP基礎.Lesson 2 description: for loop,while loop,if else tags: 1th,講義,c++,語法 --- # CPP基礎.Lesson 2 ## `if`, `eles if`, `else` 水獺今天對發票,他心裡想著 如果我中200我要喝一杯珍奶 中500想吃麥當當 中1000萬想要環遊世界 但是因為他很健忘常常忘記 於是他寫下了這個程式 ```cpp= #include <iostream> using namespace std; int main() { int money = 0; cin >> money; if( money == 200 ){//== 比較左右兩邊的值 cout << "喝珍奶" << endl; } else if( money == 500 ){ cout << "吃麥當當" << endl; } else if( money == 10000000 ){ cout << "環遊世界" << endl; } else{ cout << "生氣氣" << endl; } } ``` :::info 語法教室 :mega: #### `if`: true 就會執行{}內的code ```cpp if( 條件 ){ 如果條件成立要做的事... } ``` #### `else`: if條件不成立時要做的事(一定要接在if後面) ```cpp else{ 要做的事... } ``` #### `else if`: 夾在`if`和`else`中間,用法同`if`,但是最多只會執行其中一個`{ }`內的程式。通常用在多種情況選一種的時候。 ```cpp if( 條件 ){ 如果條件成立要做的事... } else if( 條件1 ){ 要做的事... } else if( 條件2 ){ 要做的事... } else if( 條件3 ){ 要做的事... } else{ 要做的事... } ``` 可以使用`>`,`==`,`<`來當作條件 像是`a>b`之類的 :::danger 在程式的世界裡`==`是比較兩邊的值一不一樣 `=`是把右邊的值複製一份給左邊 兩者不太一樣要注意唷 ::: ## `for` loop 假設今天我們想要印出10行`我想躺躺`我們可以這麼做 > 我好累好累我要天天躺躺[name=水獺][time=Wed, May 19, 2021 8:34 PM][color=#FBBC05] ```cpp= #include <iostream> using namespace std; int main() { cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; cout << "我想躺躺" << endl; } ``` 但是如果一次想印100行,總不能永遠的copy paste 吧 所以就發明了loop(迴圈)來幫助我們執行重複的指令~ 我們只需將程式寫成這樣 ```cpp= #include <iostream> using namespace std; int main() { for(int i=0; i<10; i++){ cout << "我想躺躺" << endl; } } ``` :::info 語法教室 :mega: ##### `for` loop 在... 做什麼事 ```cpp for( 一開始先做什麼事; 條件; 每執行完一次{}內的code,就做什麼事){ 要重複做的事... } ``` ::: ### 小練習 [a244: 新手訓練 ~ for + if](https://zerojudge.tw/ShowProblem?problemid=a244) ## `while` loop 水獺抱怨完了 是時候補充能量了!! :stuck_out_tongue_closed_eyes::stuck_out_tongue_closed_eyes::stuck_out_tongue_closed_eyes: ```cpp= #include <iostream> using namespace std; int main() { int energy=0; while( energy < 100 ){ bool comfortable; cin >> comfortable; if( comfortable == true ){//== 比較左右兩邊的值 energy++; } else{ cout << "生氣氣" << endl; } } cout << "充飽電ㄌ" << endl; } ``` :::info 語法教室 :mega: ##### `while` loop true 就會執行`{ }`內的code ```cpp while( 條件 ){ 要重複做的事... } ``` ::: ## 回家作業 [d072: 格瑞哥里的煩惱 (Case 版) ](https://zerojudge.tw/ShowProblem?problemid=d072) [c420: Bert的三角形 (3) ](https://zerojudge.tw/ShowProblem?problemid=c420)