sunfrancis12
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Ch05 for 迴圈 > 上一章: [Ch04 while 迴圈](https://hackmd.io/@sunfrancis12/BJB6lCiG6) > 下一章: [Ch06 函式庫、格式化輸出](https://hackmd.io/@sunfrancis12/SyVV-RoGT) > 回目錄: [NTCU程式戰鬥營C講義](https://hackmd.io/@sunfrancis12/ByfdXdjG6) ## while迴圈 vs for迴圈 for迴圈跟while的概念差不多,都是迴圈結構的一種,兩者之間的使用邏輯相同 只是for又比while再多了一些選項,使在某些場合使用起來會比while更直觀且方便理解 ```c= for(int i=0;i<10;i++) ``` ## for迴圈定義 語法: ```c= for ( init-expression ; cond-expression ; loop-expression ) ``` 語法解釋: :::info 注意!!! 以下的內容都是可選擇性的,並非是一個for迴圈必要的 詳細的內容會在後面章節介紹 ::: ![image.png](https://hackmd.io/_uploads/rJoLZ7rmp.png) > [圖片取自: for statement (C++)-Mircosoft](https://learn.microsoft.com/zh-tw/cpp/cpp/for-statement-cpp?view=msvc-170) ## for的使用 通常我們使用for迴圈的時機,是我們需要一個迴圈的索引值(`i`,`j`...)來幫助我們做一些運算 使用範例: * 設定一個for變數`i`,初始化為0 * 當`i<10`的條件滿足時,迴圈繼續執行 * 迴圈開始時執行`i++` ```c= for(int i=0;i<10;i++) ``` ## for迴圈實作 我們寫一個從1印到10的程式,比較一下for跟while寫法的差異: 可以看到有一個陣列索引值在這種需要累加或者循序的程式上,使用起來會方便許多 * while版本 ```c= #include<stdio.h> int main(){ int num=1; while(num<=10){ printf("%d ",num); num++; } } ``` * for版本 ```c= #include<stdio.h> int main(){ for(int i=1;i<=10;i++){ printf("%d ",i); } } ``` 輸出結果: ```c= 1 2 3 4 5 6 7 8 9 10 ``` 我們也可以使用for來寫一個判斷數字是否為質數的程式 ```c= #include<stdio.h> int main(){ int num; printf("請輸入一個數字: "); scanf("%d",&num); int sum=0; //sum為因數(扣掉1和自己)的數量 for(int i=2;i<num;i++){ if(num%i==0) sum++; } if(sum>0 || num==1) printf("%d 不是質數",num); else printf("%d 是質數",num); } ``` <a style="color:green">【小觀念】</a> 正如前面for迴圈的定義所說,for迴圈的`cond-expression`就跟if跟while那些一樣,是可以使用多重條件的,而且結束的條件也未必要和迴圈索引值(`i`,`j`)有關 ```c= for(int i=1;i<=1000 && a>10;i++) ``` ## 巢狀迴圈 巢狀迴圈顧名思義代表復數的迴圈,而且一層包著一層 ```c= for(){ for(){ for{ ....... } } } ``` 巢狀迴圈的執行的順序: ```c= #include<stdio.h> int main(){ for(int i=1;i<=3;i++){ printf("我是外部迴圈執行第%d次\n",i); for(int j=1;j<=3;j++){ printf("我是內部執行第%d次\n",j); } } } ``` 輸出結果: ```c= 我是外部迴圈執行第1次 我是內部執行第1次 我是內部執行第2次 我是內部執行第3次 我是外部迴圈執行第2次 我是內部執行第1次 我是內部執行第2次 我是內部執行第3次 我是外部迴圈執行第3次 我是內部執行第1次 我是內部執行第2次 我是內部執行第3次 ``` <a style="color:orange">【例題】</a> > 利用雙層迴圈印出一個99乘法表 範例程式: ```c= #include<stdio.h> int main(){ for(int i=1;i<=9;i++){ for(int j=1;j<=9;j++){ printf("%dx%d= %d ",i,j,i*j); } printf("\n"); } } ``` 輸出結果: ```c= 1x1= 1 1x2= 2 1x3= 3 1x4= 4 1x5= 5 1x6= 6 1x7= 7 1x8= 8 1x9= 9 2x1= 2 2x2= 4 2x3= 6 2x4= 8 2x5= 10 2x6= 12 2x7= 14 2x8= 16 2x9= 18 3x1= 3 3x2= 6 3x3= 9 3x4= 12 3x5= 15 3x6= 18 3x7= 21 3x8= 24 3x9= 27 4x1= 4 4x2= 8 4x3= 12 4x4= 16 4x5= 20 4x6= 24 4x7= 28 4x8= 32 4x9= 36 5x1= 5 5x2= 10 5x3= 15 5x4= 20 5x5= 25 5x6= 30 5x7= 35 5x8= 40 5x9= 45 6x1= 6 6x2= 12 6x3= 18 6x4= 24 6x5= 30 6x6= 36 6x7= 42 6x8= 48 6x9= 54 7x1= 7 7x2= 14 7x3= 21 7x4= 28 7x5= 35 7x6= 42 7x7= 49 7x8= 56 7x9= 63 8x1= 8 8x2= 16 8x3= 24 8x4= 32 8x5= 40 8x6= 48 8x7= 56 8x8= 64 8x9= 72 9x1= 9 9x2= 18 9x3= 27 9x4= 36 9x5= 45 9x6= 54 9x7= 63 9x8= 72 9x9= 81 ``` <a style="color:orange">【例題】</a> > 輸入一串數字,並判斷其是否為質數 > 輸入0的話則程式中止並輸出總共輸入多少質數 範例輸入: ```c= 17 24 46 81 47 59 63 0 ``` 範例輸出: ```c= 請輸入數字: 17 17 是質數 請輸入數字: 24 24 不是質數 請輸入數字: 46 46 不是質數 請輸入數字: 81 81 不是質數 請輸入數字: 47 47 是質數 請輸入數字: 59 59 是質數 請輸入數字: 63 63 不是質數 請輸入數字: 0 總共輸入了3個質數 ``` 範例程式: ```c= #include<stdio.h> int main(){ int num,count=0; printf("請輸入數字: "); while(scanf("%d",&num)){ if(num==0) break; int sum=0; //sum為因數(扣掉1和自己)的數量 for(int i=2;i<num;i++){ if(num%i==0) sum++; } if(sum>0 || num==1){ printf("%d 不是質數\n",num); }else{ printf("%d 是質數\n",num); count++; } printf("請輸入數字: "); } printf("總共輸入了%d個質數",count); } ``` --- > 上一章: [Ch04 while 迴圈](https://hackmd.io/@sunfrancis12/BJB6lCiG6) > 下一章: [Ch06 函式庫、格式化輸出](https://hackmd.io/@sunfrancis12/SyVV-RoGT) > 回目錄: [NTCU程式戰鬥營C講義](https://hackmd.io/@sunfrancis12/ByfdXdjG6)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully