思路

  1. for loop 用的時機
  2. while loop 用的時機
  3. recursion 用的時機

實作

for loop: 用於知道確切迴圈數

int[] nums = new int[]{1,2,3,4,5,6,7};
for (int i = 0; i <= nums.length;i++) {
    System.out.println(i);
}

while loop: 用於無法得知確切迴圈數

int winning_number = 777;
while(true) {
    int random_number = (int) (1000 * Math.random());
    if (random_number == winning_number) {
        System.out.println("Congratulation!");
        break;
    }
}

Recursion: 呼叫自身方法執行

// fibonacci
public static Integer fibonacci(int n){
    if (n == 0) return 0;   // first number
    if (n == 1) return 1;   // second number

    /** next round **/
    return fibonacci(n - 2) + fibonacci(n - 1);
}

for (int i = 0; i < 20; i++) {
    System.out.print(fibonacci(i) + " "); 
    // 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 
}