Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 6.13 Chapter Summary

Subsection 6.13.1 Technical Term

conditional loop loop bound sentinel bound
counting loop loop entry condition unit indexing
do-while statement nested loop updater
infinite loop postcondition while statement
initializer precondition zero indexing
limit bound priming read
loop body repetition structure

Subsection 6.13.2 Summary of Important Points

  • A repetition structure is a control structure that allows a statement or sequence of statements to be repeated.
  • All loop structures involve three elements—an initializer, a loop entry condition or a loop boundary condition, and an updater.
  • When designing a loop, it is important to analyze the loop structure to make sure that the loop bound will eventually be satisfied.
  • The for statement has the following syntax:
    for (  initializer ;  loop entry condition ; updater )
    {  
        for loop body 
    }
    
    A summary of various loop bounds:
    Bound Example
    Counting k \(\lt\) \(100\)
    Sentinel input != 9999
    Flag done != true
    Limit amount \(\lt\) \(0.5\)
  • The while statement takes the following form:
    while ( loop entry condition )
    {
        loop body
    }
    
  • The do-while statement has the following general form:
    do
    { 
        loop body 
    } while ( loop condition );
    
  • When designing a loop, it is important to analyze the loop structure to make sure that the loop bound will eventually be satisified. The table below summarizes the types of loop bounds that we have identified.
  • Structured programming is the practice of writing programs that are built up from a small set of predefined control structures—the sequence, selection, repetition, and method-call structures. An important feature of these structures is that each has a single entry and exit.
  • A precondition is a condition that must be true before a certain code segment executes. A postcondition is a condition that must be true when a certain code segment is finished. Preconditions and postconditions should be used in the design, coding, documentation, and debugging of algorithms and methods.

Solutions 6.13.3 Solutions to Self-Study Exercises

6.3 Counting Loops
6.3.7 Self-Study Exercises

6.3.7.1. For Loop Bugs 1.
Solution.
Bug: Commas are used instead of semicolons in the header. Loop fixed below.
for (int k = 5; k < 100; k++)
   System.out.println(k);
6.3.7.2. For Loop Bugs 2.
Solution.
Bug: There shouldn’t be 3 semicolons in the header. Loop fixed below.
for (int k = 0; k < 12 ; k--)
    System.out.println(k);
6.3.7.3. Infinite Loops.
Solution.
  1. Infinite loop because k is never incremented.
  2. Infinite loop because k is always odd and thus never equal to 100.
6.3.7.4. Variable j in Loop.
Solution.
j will be undefined when the loop terminates. It is a local variable whose scope is limited to the loop body.
6.3.7.5. Count by 4’s.
Solution.
Your sister is learning to count by fours. Write a for loop that prints the following sequence of numbers: 1, 5, 9, 13, 17, 21, 25.
for (int k = 1; k <= 25; k = k+4)
  System.out.print(k + " ");

6.3.8 Nested Loops

Self-Study Exercise
6.3.8.1. Nested Loop Pattern.
Solution.
Write a nested for loop to print the following geometric pattern:
#
# #
# # #
# # # #
# # # # #
for (int row = 1; row <= 5; row++)  {    // For each row
  for (int col = 1; col <= row; col++) // Columns per row
      System.out.print('#');
  System.out.println();                // New line
} // row

6.6 Conditional Loops
6.6.1 The While Structure, Revisited

Self-Study Exercises
6.6.1.1. While Loop Bugs 1.
Solution.
int k = 5;
while (k < 20) {
    System.out.println(k);
    k++                     << Missing semicolon
  }
6.6.1.2. While Loop Bugs 2.
Solution.
int k = 0;
while (k < 12;) {           << Extra semicolon
    System.out.println(k);
    k++;
  }
6.6.1.3. While Loop Bugs 3.
Solution.
Infinite Loop. k needs to be changed in the loop. Fixed:
int k = 0;
while (k < 10) 
{
    System.out.println(k);
    k++;  // add increment counter k and { } in loop body.
}
6.6.1.4. While Loop Bugs 4.
Solution.
Missing initializer for k. Add k = 0; or some initial value.
int k = 0;  << Missing initializer
while (k < 10) {          
  System.out.println(k);
  k++;
 }
6.6.1.5. Count by 6’s.
Solution.
Your younger sister is now learning how to count by sixes. Write a while loop that prints the following sequence of numbers: 0, 6, 12, 18, 24, 30, 36.
int k = 0;                 // Initializer
while (k <= 36) {          // Loop-entry condition
 System.out.println(k);
 k += 6;                  // Updater
}
6.6.1.6. While Sequence.
Solution.
If N is even, divide it by 2. If N is odd, subtract 1 and then divide it by 2. This will generate a sequence that is guaranteed to terminate at 0. For example, if N is initially 15, then you get the sequence 15, 7, 3, 1, 0. Write a method that implements this sequence using a while statement.
public static void sub1Div2(int N) {
  while(N != 0) {
    System.out.print(N + " ");
    if (N % 2 == 0)
        N = N / 2;
    else
        N = (N - 1) / 2;
  }
  System.out.println( N );
} // sub1Div2()

6.6.2 The Do-While Structure

Self-Study Exercises
6.6.2.1. Do While Loop Bugs 1.
Solution.
int k = 0;
do while (k < 100) << Misplaced condition
{
     System.out.println(k);
     k++;
}                    << Belongs here
6.6.2.2. Do While Loop Bugs 2.
Solution.
int k = 0;
do {
    System.out.println(k);
    k++;
} while (k < 12) << Missing semicolon
6.6.2.3. Count by 7’s.
Solution.
Your sister has moved on to counting by sevens. Write a do-while loop that prints the following sequence of numbers: 1, 8, 15, 22, 29, 36, 43.
n = 1;      // Initializer
do {
  System.out.print(n + " ");
  n += 7;                 // Updater
} while (n <= 43);     // Loop re-entry condition
6.6.2.4. Pizza Costs.
Solution.
Write a method to input and validate pizza sales.
public int getAndValidatePizzaPrice() { // Uses KeyboardReader
  int pizza = 0;
  do {
    reader.prompt("Input a pizza price (8, 10, or 15) ");
    reader.prompt("or 99 to end the list >> ");
    pizza = reader.getKeyboardInteger();
    if ((pizza != 99) && (pizza != 8) && (pizza != 10) && (pizza != 15))
      System.out.println("Error: you've entered an "
       + "invalid pizza price\n");    // Error input
    else                               // OK input
        System.out.println("You input " + pizza + "\n");
  } while ((pizza != 99) && (pizza != 8) && (pizza != 10) && (pizza != 15));
  return pizza;
} // getAndValidatePizzaPrice()
6.6.2.5. Pizza Codes.
Solution.
Write a method to input and validate pizza sales using the numbers 1, 2, and 3 to represent pizzas at different price levels.
public int getAndValidatePizzaPrice() { // Uses KeyboardReader
  int pizza = 0;
  do {
    reader.prompt("Input a 1,2 or 3 to indicate pizza"
              + "price ( 1(8), 2(10), or 3($15) ) ");
    reader.prompt("or 0 to end the list >> ");
    pizza = reader.getKeyboardInteger();
    if ((pizza < 0) || (pizza > 3))  // Error check
        System.out.println("Error: you've entered an "
                                + "invalid value\n");
    else                                // OK input
        System.out.println("You input " + pizza + "\n");
  } while ( (pizza < 0) || (pizza > 3) );
  if (pizza == 1)
    return 8;
  else if (pizza == 2)
    return 10;
  else if (pizza == 3)
    return 15;
  else
    return 0;
  } // getAndValidatePizzaPrice()

6.9 Principles of Loop Design
6.9.1 Loop Summary

Self-Study Exercise
6.9.1.1. Loop Choices.
Solution.
For each of the following problems, decide whether a counting loop structure, a while structure, or a do-while structure should be used, and write a pseudocode algorithm.
  1. Printing the names of all the visitors to a Web site could use a counting loop because the exact number of visitors is known.
    for each name in the visitor's log
       print the name
    
  2. Validating that a user has entered a positive number requires a do-while structure in which you repeatedly read a number and validate it.
    do
      read a number
      if number is invalid, 
         print error message
    while number is invalid
    
  3. Changing all the backslashes (\(\backslash\)) in a Windows Web page address, to the slashes (/) used in a Unix Web page address.
    for each character in the Web page address
       if it is a backslash 
          replace it with slash
    
  4. Finding the largest in a list of numbers requires a while loop to guard against an empty list.
    initialize maxMPG to smallest possible number
    while there are more cars in the database
       if current car's MPG is greater than maxMPG
          replace maxMPG with it
    

6.10 The switch Multiway Selection Structure
6.10.1 Switch

Self-Study Exercises
6.10.1.1. Switch Bug 1.
Solution.
int k = 0;
switch (k)  // Syntax error: missing braces
 case 0:
     System.out.println("zero");
     break;
 case 1:
     System.out.println("one");
     break;
 default:
     System.out.println("default");
     break;
}
6.10.1.2. Switch Bug 2.
Solution.
int k = 0;
switch (k + 1)
{
    case 0:
        System.out.println("zero");
        break;               // Missing break;
    case 1:
        System.out.println("one"); 
        break;           // Missing break;
    default:
        System.out.println("default");
        break;         // Missing break;
}
6.10.1.3. Switch Bug 3.
Solution.
int k = 6;
switch (k / 3.0) // Syntax error: not an integral value
{
    case 2:
        System.out.println("zero");
        break;
    case 3:
        System.out.println("one");
        break;
    default:
        System.out.println("default");
        break;
}
6.10.1.4. Ice Cream Flavors.
Solution.
switch (flavor)
{
    case 1:
        System.out.println("Vanilla");
        break;
    case 2:
        System.out.println("Chocolate");
        break;
    case 3:
        System.out.println("Strawberry");
        break;
    default:
        System.out.println("Error");
}

6.11 OBJECT-ORIENTED DESIGN: Structured Programming
6.11.4 Effective Program Design

Self-Study Exercises
6.11.4.1. Pre/Post Conditions 1.
Solution.
Identify the pre- and postconditions on j and k where indicated in the following code segment:
int j = 0; k = 5;
do {
    if (k % 5 == 0) {
                      // Precondition: j <= k
        j += k;
        k--;
    }
    else k *= k;
  } while (j <= k);
                      // Postcondition: j > k
6.11.4.2. Pre/Post Conditions 2.
Solution.
Identify the pre- and postconditions for the following method, which computes \(x^n\) for \(n >= 0\text{.}\)
// Precondition: N >= 0
// Postcondition: power(x,n) == x to the n
public double power(double x, int n ) {
    double pow = 1;
    for (int k = 1; k <= n; k++)
        pow = pow * x;
    return pow;
} // power()
You have attempted of activities on this page.