next up previous contents
Next: if...else statement Up: 判斷 Previous: 前言   Contents

if statement

  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) {condition code};
\node [cir,below of=code] (sum) {};
\node [output,below of=sum] (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) -- (sum);
\path [line] (sum) -- (output);
\end{tikzpicture}

  2. 語法
    if(boolean_expression)
    {
       /* statement(s) will execute if the boolean expression is true */
    }
    
  3. 範例
    [dywang@dyw219 zzz]$ vim if1.c
    [dywang@dyw219 zzz]$ cat if1.c
    #include <stdio.h>
    
    main() {
        int a;
    
        printf("Enter an integer: ");
        scanf("%d", &a);
    
        if ( a>10 ) {
    		printf("%d > 10\n", a);
    	}
        printf("a = %d\n", a );
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o if1 if1.c
    
  5. 執行結果一
    [dywang@dyw219 zzz]$ ./if1
    Enter an integer: 3
    a = 3
    
  6. 執行結果二
    [dywang@dyw219 zzz]$ ./if1
    Enter an integer: 13
    13 > 10
    a = 13
    



De-Yu Wang 2019-08-14