next up previous contents
Next: 無窮迴圈 Up: 迴圈 Previous: while loop   Contents

do...while loop

  1. 流程圖

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

  2. 語法:先進入迴圈執行一次,condition 再判斷是否成立?成立則繼續執行迴圈。
    do {
       statement(s);
    
    }while( condition );
    
  3. 範例:承上例輸入一數字,從 1 累加到總數超過此數字。但使用 do...while 迴圈讓用戶輸入正整數為止。
    [dywang@dyw219 zzz]$ vim dowhile1.c
    [dywang@dyw219 zzz]$ cat dowhile1.c 
    #include <stdio.h>
    
    main() {
    	int i=1, a, sum=0;
    
    	do {
    		printf("Enter an integer: ");
    		scanf("%d", &a);
    	} while ( a<=0 );
    
    	while ( sum < a ) {
    		printf("%d+", i++ );
    		sum += i;
    	}
    	printf("%d=%d\n", i,sum );
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o dowhile1 dowhile1.c
    
  5. 執行結果:輸入 0 或 -3 程式持續要求輸入一整數,直到輸入正整數 25 時才計算總合並輸出。
    [dywang@dyw219 zzz]$ ./dowhile1
    Enter an integer: 0
    Enter an integer: -3
    Enter an integer: 25
    1+2+3+4+5+6+7=27
    



De-Yu Wang 2019-08-14