Source of 4.2.java


  1: // @author Frank M. Carrano, Timothy M. Henry
  2: // @version 5.0
  3: // Computing the sum of the consecutive integers from 1 to n:
  4: long n = 10000; // ten thousand

  6: // Algorithm A
  7: long sum = 0;
  8: for (long i = 1; i <= n; i++)
  9:    sum = sum + i;
 10: System.out.println(sum);

 12: // Algorithm B
 13: sum = 0;
 14: for (long i = 1; i <= n; i++)
 15: {
 16:    for (long j = 1; j <= i; j++)
 17:       sum = sum + 1;
 18: } // end for
 19: System.out.println(sum);

 21: // Algorithm C
 22: sum = n * (n + 1) / 2;
 23: System.out.println(sum);