Skip to main content

Section 8.1 Worked Example: Writing Loops Part 1

Subgoals for Writing a Loop.

  1. Determine purpose of loop
    1. Pick a loop structure (while, for, do_while)
  2. Define and initialize variables
  3. Determine termination condition
    1. Invert termination condition to continuation condition
  4. Write loop body
    1. Update loop control variable to reach termination

Subsection 8.1.1

You can watch this video or read through the content below it. For this specific problem skip to 3:10 in the video.
Problem: Write a loop that will add up 1 + 1/2 + 1/4 + 1/8 + 1/16 + … + 1/1024

Subsection 8.1.2 SG1: Determine purpose of loop

Because we know the number of iterations, we could choose a for-loop, but for this exercise we will go with the general purpose while-loop.

Subsection 8.1.3 SG2: Define and initialize variables

double sum = 0;
double term = 1.0;
while (        )
{

}
System.out.println(sum);

Subsection 8.1.4 SG3: Define termination condition invert to continuation condition

The denominators are increasing powers of 2. The first denominator, if you think of 1 as 1/1, is 2 raised to the power of 0. The final denominator, 1024, is 2 raised to the power of 10, so we will iterate from zero to ten. We know we need to iterate 10 times, from the variable i starting a 0 and it should end when i is 11. To convert (i >= 11) to a termination condition, it becomes (i <= 10) so the code is:
double sum = 0;
double term = 1.0;
int i = 0;
while ( i <= 10 )
{

}
System.out.println(sum);

Subsection 8.1.5 SG4: Write loop body

double sum = 0;
double term = 1.0;
int i = 0;

while ( i <= 10 )
{
   sum = sum + term;
   term = 0.5 * term; //same as divide term in half
   i++;
}
System.out.println(sum);
Here is the equivalent for loop approach to solve this problem:
double sum = 0;
double term = 1.0;
for (int i = 0; i <= 10; i++) {
    sum =  sum + term;
    term = 0.5 * term;
}
System.out.println(sum);

Practice Pages.

You have attempted of activities on this page.