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

nested if statements

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



De-Yu Wang 2019-09-19