巢式迴圈

  1. 巢式迴圈 (nested loops) 是指迴圈中還有迴圈,以下有 for, while, do...while 等巢式迴圈語法,當然 for 迴圈內可以有 while, do...while 等迴圈,也就是各種組合的巢式迴圈,且可以好幾層。
  2. nested for loop 語法:
    for ( init; condition; increment ) {
       for ( init; condition; increment ) {
          statement(s);
       }
       statement(s);
    }
    
  3. nested while loop 語法
    while(condition) {
       while(condition) {
          statement(s);
       }
       statement(s);
    }
    
  4. nested do...while loop 語法
    do {
       statement(s);
       do {
          statement(s);
       } while( condition );
    
    }while( condition );
    
  5. 範例:輸入一整數,列印小於這整數的所有質數 (prime)。
    [dywang@deyu zzz]$ vim nestedfor1.c
    [dywang@deyu zzz]$ cat nestedfor1.c
    #include <stdio.h>
    
    int main() {
    	int i, j, a;
    
    	printf("Enter an integer: ");
    	scanf("%d", &a);
    
    	for ( i=2; i<a; i++) {
    		for ( j=2; j<=i/j; j++ )
    			if (!(i%j)) break; // if factor found, not prime
    		if ( j > i/j ) printf("%d is prime\n", i);
    	}
    }
    
  6. 編譯成功
    [dywang@deyu zzz]$ gcc -o nestedfor1 nestedfor1.c
    
  7. 執行結果
    [dywang@dywIssd zzz]$ ./nestedfor1 
    Enter an integer: 10
    2 is prime
    3 is prime
    5 is prime
    7 is prime
    [dywang@dywIssd zzz]$ ./nestedfor1 
    Enter an integer: 100
    2 is prime
    3 is prime
    5 is prime
    7 is prime
    11 is prime
    13 is prime
    17 is prime
    19 is prime
    23 is prime
    29 is prime
    31 is prime
    37 is prime
    41 is prime
    43 is prime
    47 is prime
    53 is prime
    59 is prime
    61 is prime
    67 is prime
    71 is prime
    73 is prime
    79 is prime
    83 is prime
    89 is prime
    97 is prime