next up previous contents
Next: do...while loop Up: 迴圈 Previous: for loop   Contents

while loop

  1. 流程圖

    \begin{tikzpicture}[node distance=1.5cm,auto]\setlength \baselineskip{1ex}
\node [input,name=input] {};
\node [decision, below of=input] (decision) {condition?};
\node [block, below of=decision] (code) {block code};
\node [cir,below of=code] (sum) {};
\node [output,below of=sum,name=output] {};
\path [line] (input) --(decision);
\path [line] (decision) -- node[right]{true}(code);
\path [line] (decision.east) -\vert node[right] {false} ($(decision.east) + (1.5,0)$) \vert- (sum.east);
\path [line] (code) \vert- node[]{} ($(code.west)+(-1.5,-1)$) \vert-(decision.west);
\path [line] (sum) -- (output);
\end{tikzpicture}

  2. 語法: condition 判斷條件是否成立,成立則繼續執行迴圈。
    while(condition)
    {
       statement(s);
    }
    
  3. 範例:輸入一數字,從 1 累加到總數超過此數字。
    [dywang@dyw219 zzz]$ vim while1.c 
    [dywang@dyw219 zzz]$ cat while1.c 
    #include <stdio.h>
    
    main() {
    	int i=1, a, sum=0;
    
    	printf("Enter an integer: ");
    	scanf("%d", &a);
    
    	while ( sum < a ) {
    		printf("%d+", i++ );
    		sum += i;
    	}
    	printf("%d=%d\n", i,sum );
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o while1 while1.c
    
  5. 執行結果一:輸入正整數時,輸出正確。
    [dywang@dyw219 zzz]$ ./while1
    Enter an integer: 23
    1+2+3+4+5+6+7=27
    [dywang@dyw219 zzz]$ ./while1
    Enter an integer: 76
    1+2+3+4+5+6+7+8+9+10+11+12=77
    Enter an integer: 10
    1+2+3+4+5+6+7+8+9+10=55
    
  6. 執行結果二:輸入 0 或負數時,輸出變成 1=0?
    [dywang@dyw219 zzz]$ ./while1
    Enter an integer: -3
    1=0
    [dywang@dyw219 zzz]$ ./while1
    Enter an integer: 0
    1=0
    



De-Yu Wang 2019-09-19