# 第三章、迴圈 迴圈(loop)意旨會重複做某件事 例如:求和,找因數等常用功能 非常非常重要的一個單元 ## while loop while迴圈常用於不確定會做幾次,僅僅只需做條件判斷的功能 ::: success ```cpp= 語法: 1.常用: while(條件式) { 執行內容 } 2.無限迴圈 while(1) { 執行內容,通常會搭配if和等等會教的break } 3.EOF結尾(讀取到檔案結尾),常常在各大評測系統出現 while(cin>>n) { 執行內容 } ``` ::: :::danger 其實cin可以當作會回傳bool值,當有輸入時回傳ture(1)否則回傳false(0)*(實際上並非如此,背後有非常複雜的原理,可以自行查閱了解)*,在測試時可用Ctrl+Z當檔案結尾 ::: :::info 例題 [d070. 格瑞哥里的煩惱 (0 尾版)](https://zerojudge.tw/ShowProblem?problemid=d070) 由題目可以知道條件的判斷可以這樣做 ```cpp= if(n%100!=0&&n%4==0) a leap year else if(n%400==0) a leap year else a normal year ``` 並且,迴圈的結束條件應該要是n==0 所以可以得到 ```cpp= while(cin>>n&&n!=0) ``` 將兩者結合後可以並且補上基礎輸出輸入後可以得到正確答案 ```cpp= #include<bits/stdc++.h> using namespace std; int main() { int n; while(cin>>n) { if(n==0) break; if(n%4==0&&n%100!=0) cout<<"a leap year"<<endl; else if(n%400==0) cout<<"a leap year"<<endl; else cout<<"a normal year"<<endl; } } ``` ::: :::warning [a010. 因數分解](https://zerojudge.tw/ShowProblem?problemid=a010) ```cpp= while(cin>>n)//EOF ``` ::: :::warning [d071. 格瑞哥里的煩惱 (EOF 版)](https://zerojudge.tw/ShowProblem?problemid=d071) 題目內容是與上題一樣,這題主要是EOF結尾的用法 ```cpp= while(cin>>n)//EOF ``` ::: ## for loop for迴圈常用於明確了解運算次數,與while來說更為常用,但對於初學者來說需要多練習才能熟悉。 :::success ```cpp= 語法: 1.常用: for(初始值;條件式;每次條件式成立後執行) { 執行內容 } 2.無限迴圈(很少使用,通常以while表示) for(初始值;1/true;執行) { 執行內容,通常會搭配if和等等會教的break } ``` ::: :::info 例題 [a058. MOD3](https://zerojudge.tw/ShowProblem?problemid=a058) 一開始會給一個n值,可以用n為上限當作結束條件,常用以$i$作為變數 ```cpp= #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int k=0,kk=0,kkk=0; /* k表示mod3=0 kk表示mod3=1 kkk表示mod3=2 */ for(int i=0;i<n;i++) { int z; cin>>z; if(z%3==0) k++; if(z%3==1) kk++; if(z%3==2) kkk++; } cout<<k<<' '<<kk<<' '<<kkk<<endl; } ``` ::: :::info [d074. 電腦教室](https://zerojudge.tw/ShowProblem?problemid=d074) 尋找最大值的基本模板!! ```cpp= #include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int maxs=-1; for(int i=0;i<n;i++) { int a; cin>>a; maxs=max(a,maxs); } cout<<maxs; } ``` ::: :::warning [a004. 文文的求婚](https://zerojudge.tw/ShowProblem?problemid=a004) ::: :::warning [a005. Eva 的回家作業](https://zerojudge.tw/ShowProblem?problemid=a005) ::: :::warning [d490. 我也愛偶數](https://zerojudge.tw/ShowProblem?problemid=d049) ::: :::warning [d498. 我不說髒話](https://zerojudge.tw/ShowProblem?problemid=d498) ::: :::warning [c290. APCS 2017-0304-1秘密差](https://zerojudge.tw/ShowProblem?problemid=c290)[偏難] **APCS 2017.3 I** ::: :::warning [b964. 1. 成績指標](https://zerojudge.tw/ShowProblem?problemid=b964)[超難] **APCS 2016.3 I** :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up