next up previous contents
Next: switch statement 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. 範例
    #include <stdio.h>
     
    int main ()
    {
       /* local variable definition */
       int a = 100;
     
       /* check the boolean condition */
       if( a == 10 )
       {
           /* if condition is true then print the following */
           printf("Value of a is 10\n" );
       }
       else if( a == 20 )
       {
           /* if else if condition is true */
           printf("Value of a is 20\n" );
       }
       else if( a == 30 )
       {
           /* if else if condition is true  */
           printf("Value of a is 30\n" );
       }
       else
       {
           /* if none of the conditions is true */
           printf("None of the values is matching\n" );
       }
       printf("Exact value of a is: %d\n", a );
     
       return 0;
    }
    



2015-01-16