next up previous contents
Next: nested if statements Up: 判斷 Previous: if statement   Contents

if...else statement

  1. 流程圖
    \begin{tikzpicture}[node distance=1.5cm]\setlength \baselineskip{1ex}
\node [input,name=input] {};
\node [decision, below of=input] (decision) {condition?};
\node [block, below of=decision] (truecode) {ture condition code};
\node [block, right of=truecode, node distance=4cm] (falsecode) {false condition code};
\node [cir,below of=truecode] (sum) {};
\node [output,below of=sum] (output) {};
\path [line] (input) --(decision);
\path [line] (decision) -- node[right]{true}(truecode);
\path [line] (decision.east) -\vert node[right] {false} (falsecode.north);
\path [line] (falsecode.south) \vert- (sum.east);
\path [line] (truecode) -- (sum);
\path [line] (sum) -- (output);
\end{tikzpicture}

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



De-Yu Wang 2019-08-14