Skip to main content

Section 8.4 Assessment: Writing Loops

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

Exercises Exercises

    2.

    Q2: Given the following code segment which is intended to print the number of integers that evenly divide the integer inputVal. You may assume that inputVal > 0. Which of the following can be used to replace /* condition */ so that numDivisors will work as intended?
    int count = 0;
    int inputVal = /* user entered value */
    for (int k = 1; k <= inputVal; k++) {
       if ( /* condition */ ) {
          count++;
       }
    } // end for
    System.out.println(count);
    

    4.

    Q4: What is the maximum number of times β€œHello” can be printed?
    int k = // a random number such that 1 <= k <= n ;
    for (int p = 2; p <= k; p++) {
       for (int r = 1; r < k; r++)
          System.out.println("Hello");
    }
    
You have attempted of activities on this page.