CSC300: Get your loops straight! [1/10] Previous pageContentsNext page

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class LinkedList {
  class Node { double item; Node next; }
  Node first;
  
  public double sum1 () {
    double result = 0;    
    Node current = first; // may be null
    while (current != null) {
      result = result + current.item;
      current = current.next;
    }
  }

  public double sum2 () {
    if (first == null) return 0;
    double result = first.item;    
    Node prev = first; // never null
    while (prev.next != null) {
      result = result + prev.next.item;
      prev = prev.next;
    }
  }

  public double sum3 () {
    if (first == null) return 0;
    double result = first.item;
    Node prev = first;         // never null
    Node current = first.next; // may be null
    while (current != null) {
      result = result + current.item;
      prev = prev.next;
      current = current.next;
    }
  }
}

public static double sum (double[] a) {
  double result = 0;
  int i = 0;
  while (i<a.length) {
     result = result + a[i];
     i = i + 1;
  }
}

Previous pageContentsNext page