next up previous contents
Next: 練習題 Up: 迴圈 Previous: do...while loop   Contents

nested loops

  1. nested for loop 語法
    for ( init; condition; increment )
    {
       for ( init; condition; increment )
       {
          statement(s);
       }
       statement(s);
    }
    
  2. nested while loop 語法
    while(condition)
    {
       while(condition)
       {
          statement(s);
       }
       statement(s);
    }
    
  3. nested do...while loop 語法
    do
    {
       statement(s);
       do
       {
          statement(s);
       }while( condition );
    
    }while( condition );
    
  4. 範例
    #include <stdio.h>
     
    int main ()
    {
       /* local variable definition */
       int i, j;
       
       for(i=2; i<100; 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);
       }
     
       return 0;
    }
    



2015-01-16