next up previous contents
Next: 實機練習題 Up: 迴圈 Previous: continus   Contents

巢式迴圈

  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@dyw219 zzz]$ vim nestedfor1.c
    [dywang@dyw219 zzz]$ cat nestedfor1.c
    #include <stdio.h>
    
    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@dyw219 zzz]$ gcc -o nestedfor1 nestedfor1.c
    
  7. 執行結果
    [dywang@dyw219 zzz]$ ./nestedfor1 
    Enter an integer: 10
    2 is prime
    3 is prime
    7 is prime
    [dywang@dyw219 zzz]$ ./nestedfor1 
    Enter an integer: 100
    2 is prime
    3 is prime
    7 is prime
    13 is prime
    23 is prime
    31 is prime
    43 is prime
    47 is prime
    59 is prime
    61 is prime
    73 is prime
    79 is prime
    97 is prime
    



De-Yu Wang 2019-08-14