next up previous contents
Next: 運算子 ?: Up: 判斷 Previous: nested if statements   Contents

if...else if...else Statement

  1. 流程圖
    \begin{tikzpicture}[node distance=1.5cm]\setlength \baselineskip{1ex}
\node [input,name=input] {};
\node [decision, below of=input] (decision1) {condition 1?};
\node [block, below of=decision1] (truecode1) {ture condition 1 code};
\node [decision, right of=decision1,node distance=4cm] (decision2) {condition 2?};
\node [block, right of=truecode1, node distance=4cm] (truecode2) {true condition 2 code};
\node [cir,below of=truecode2] (sum) {};
\node [output,below of=sum] (output) {};
\path [line] (input) --(decision1);
\path [line] (decision1) -- node[right]{true}(truecode1);
\path [line] (decision1) -- node[above]{false}(decision2);
\path [line] (decision2) -- node[right]{true}(truecode2);
\path [line] (decision2.east) -\vert node[right] {false}($(decision2.east)+(1,0)$) \vert- (sum.east);
\path [line] (truecode2) -- (sum);
\path [line] (truecode1.south) \vert- (sum.west);
\path [line] (sum) -- (output);
\end{tikzpicture}

  2. 語法
    if(boolean_expression 1)
    {
       /* Executes when the boolean expression 1 is true */
    }
    else if( boolean_expression 2)
    {
       /* Executes when the boolean expression 2 is true */
    }
    else if( boolean_expression 3)
    {
       /* Executes when the boolean expression 3 is true */
    }
    else 
    {
       /* executes when the none of the above condition is true */
    }
    
  3. 範例
    [dywang@dyw219 zzz]$ vim if4.c 
    [dywang@dyw219 zzz]$ cat if4.c 
    #include <stdio.h>
    
    main() {
        int a;
    
        printf("Enter an integer: ");
        scanf("%d", &a);
    
        if ( a>10 ) {
    		printf("%d > 10\n", a);
    	}	
    	else if ( a<10) {
    		printf("%d < 10\n", a);
    	}	
        else {
    		printf("a = 10\n");
    	}
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o if4 if4.c
    
  5. 執行結果一
    [dywang@dyw219 zzz]$ ./if4
    Enter an integer: 20
    20 > 10
    
  6. 執行結果二
    [dywang@dyw219 zzz]$ ./if4
    Enter an integer: 8
    8 < 10
    
  7. 執行結果三
    [dywang@dyw219 zzz]$ ./if4
    Enter an integer: 10
    a = 10
    



De-Yu Wang 2019-08-14