CSC300: Code variations: Loop version (cautious, forward) [17/37] Previous pageContentsNext page

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  public static int numFives (double[] list) {
    if (list.length == 0) return 0;
    int result = 0;
    int i = 0;


    do {
      if (list[i] == 5) {
        result++;
      }
      i = i + 1;
    } while (i < list.length);

    return result;
  }

For [5,11,5,5], the loop values (lines 17 and 24) are

list[i..]==[5,11,5,5], result==0
  list[i..]==[11,5,5], result==1
     list[i..]==[5,5], result==1
       list[i..]==[5], result==2
        list[i..]==[], result==3

Here, we first test that the list is non-empty, only entering the loop in this case. This is called cautious execution. We only enter the loop if we know it is necessary.

For both loops and tail-recursions, we can choose the style:

  • Optimistic / cautious

Beginning programmers often mix the cautious and optimistic styles. For loops this usually just causes redundant checks. For example, using a while loop in the example above, rather than a do loop.

Previous pageContentsNext page