tags: tgirc早修book

for 迴圈

基本架構

#include <iostream> using namespace std; int main(){ for(初始動作; 是否執行迴圈的判斷條件; 下一輪開始前的動作){ 指令; } return 0; }

for 是迴圈的第二種寫法,常用於指定執行次數的時候

當一次要執行很多事時,在同個段落中可以用逗號分隔
而如果什麼事都不需要做,可以只留下分號就好

範例 1
試著印出 1~5 吧

#include <iostream> using namespace std; int main(){ int i; for(i = 1; i <= 5; i++){ cout<<i<<"\n"; } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這段程式碼表示,一開始宣告一個 i,在迴圈開始前先把 i 指定為 1,當 i <= 5 時,i = i+1,每跑一次就加一次

範例 2
找看看 n 是否為完全平方數

#include <iostream> using namespace std; int main(){ int n; cin>>n; int i; for(i=1; i*i<n; i++){ } if(i*i == n){ cout<<"n是完全平方數\n"; } else { cout<<"n不是完全平方數\n"; } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

因為我們要找的是 i,迴圈內不需要額外跑指令,所以可以不放東西

範例 3
輸入 n 個數,計算有多少個數字大於 n

#include <iostream> using namespace std; int main(){ int n,i,ans; cin>>n; for(i=0, ans=0; i < n; i++){ int a; cin>>a; if(a > n){ ans++; } } cout<<ans<<"\n"; return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →