Each time through the loop we add a new term into the running sum and increment i in preparation for the next trip through the loop.

  while (i <= n) {
    sum = sum + 1/(2.0*i);
    i = i + 1;

Notice the use of the floating-point constant 2.0 instead of the integer constant 2 in the denominator. We do this so that 2.0*n will also be a floating-point number, which means that the division will produce a floating-point result.

Return to lesson.

Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah