next up previous contents
Next: while loop Up: 迴圈 Previous: 前言   Contents

for loop

  1. for 迴圈流程圖
    \begin{tikzpicture}[node distance=1.5cm]\setlength \baselineskip{1ex}
\node [input,name=input] {};
\node [block, below of=input] (init) {init};
\node [decision, below of=init] (decision) {condition?};
\node [block, below of=decision] (code) {block code};
\node [block, below of=code] (increment) {increment};
\node [cir,below of=increment] (sum) {};
\node [output,below of=sum,name=output] {};
\path [line] (input) --(init);
\path [line] (init) --(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) --(increment);
\path [line] (increment) \vert- node[]{} ($(increment.west)+(-1.5,-1)$) \vert-(decision.west);
\path [line] (sum) -- (output);
\end{tikzpicture}

  2. 語法:init 設定迴圈初始值,condition 判斷條件,increment 設定增減量。初始值不只設定迴圈控制變數的起始值,還可以設定其他變數的初始值。
    for ( init; condition; increment )
    {
       statement(s);
    }
    
  3. 範例:輸入一數字,從 1 累加到輸入的數字。
    [dywang@dyw219 zzz]$ vim for1.c 
    [dywang@dyw219 zzz]$ cat for1.c 
    #include <stdio.h>
    
    main() {
    	int i, a, sum=0;
    
    	printf("Enter an integer: ");
    	scanf("%d", &a);
    
    	for ( i=1; i<a; i++) {
    		printf("%d+", i );
    		sum += i;
    	}
    	sum += i;
    	printf("%d=%d\n", i,sum );
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o for1 for1.c
    
  5. 執行結果
    [dywang@dyw219 zzz]$ ./for1 
    Enter an integer: 10
    1+2+3+4+5+6+7+8+9+10=55
    [dywang@dyw219 zzz]$ ./for1 
    Enter an integer: 8
    1+2+3+4+5+6+7+8=36
    



De-Yu Wang 2019-08-14