首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言循環結構全解析:for、while、do-while 詳細指南

     編輯:關於C語言

C語言流程控制概述

C程式預設由上而下依序執行,從 main() 起始逐行執行至結束。但實際開發中極少如此線性運作,C語言提供多種流程控制語句改變執行順序,主要包含:if 條件判斷、for 循環、while 循環與 do...while 循環。

for 循環深度解析

for 陳述句能將程式碼區塊重複執行指定次數,結構如下:

for (initial; condition; increment) {
    statement;
}

三個表達式皆為選填,執行流程:

  1. 執行 initial(通常為計數器初始化)
  2. 判斷 condition,為假(0)則結束循環,為真則執行 statement
  3. 執行 increment(通常為計數器遞增/遞減),回到步驟 2

基本範例:正向與逆向計數

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // 正向計數 1 到 20
    for (int i = 1; i <= 20; i++) {
        printf("%d\n", i);
    }
    system("pause");
    return 0;
}

正向計數輸出結果

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // 逆向計數 20 到 1
    for (int i = 20; i >= 1; i--) {
        printf("%d\n", i);
    }
    system("pause");
    return 0;
}

逆向計數輸出結果

進階用法:自定義增量、省略初始化、複雜條件

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i = 0;
    // 省略初始化,增量為 2
    for (; i <= 20; i += 2) {
        printf("%d\n", i);
    }
    system("pause");
    return 0;
}

增量為2的輸出結果

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i = 0, j = 15;
    // 複合條件:i 遞增、j 遞減
    for (; i <= 20 && j >= 0; ) {
        j--;
        printf("%d\n", i++);
    }
    system("pause");
    return 0;
}

複合條件輸出結果

巢狀 for 循環:列印矩形

#include <stdio.h>
#include <stdlib.h>

void draw_box(int row, int column) {
    int col;
    for (; row > 0; row--) {
        for (col = column; col > 0; col--) {
            printf("x");
        }
        printf("\n");
    }
}

int main(void) {
    draw_box(8, 25);
    system("pause");
    return 0;
}

矩形列印結果

while 循環詳解

while 於條件為真時持續執行區塊,結構:

while (condition) {
    statement;
}

執行流程:計算條件 → 假則結束 → 真則執行陳述句 → 回到條件判斷。

基本範例:列印 1 到 20

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int count = 1;
    while (count <= 20) {
        printf("%d\n", count);
        count++;
    }
    system("pause");
    return 0;
}

while循環輸出結果

for 與 while 等價性

for(; condition;) 等價於 while(condition)。兩者可相互轉換,但 while 需手動處理初始化與遞增。

巢狀循環與混合應用:輸入驗證

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
    int array[5];
    int ctr = 0, nbr = 0;
    
    printf("請輸入 5 個 1-10 之間的數字:\n");
    while (ctr < 5) {
        nbr = 0;
        while (nbr < 1 || nbr > 10) {
            printf("第 %d 個數字:", ctr + 1);
            scanf("%d", &nbr);
        }
        array[ctr] = nbr;
        ctr++;
    }
    
    for (ctr = 0; ctr < 5; ctr++) {
        printf("數值 %d 為 %d\n", ctr + 1, array[ctr]);
    }
    system("pause");
    return 0;
}

輸入驗證程式執行結果

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved