CIS 160 Repetition

Objectives

  • Discuss repetition concepts
  • Use repetition in Java to solve problems
  • Create for loops in Java
  • Create while loops in Java
  • Create do/while loops in Java

Repetition

  • Types of loops in Java:
    • while
    • do/while
    • for (traditional style)
    • for (new style: iterate over collections, called for-each loops)
  • loop counters: use to keep track of how many times a loop iterates
    • initialize counter before loop starts
    • test counter to see if loop continues
    • modify counter just before end of loop
  • sentinel values: a special value read in an input loop which triggers special (often terminal) processing
  • pre-test loop: the test to see if the loop should continue happens at the start of the main loop code
  • post-test loop: the test to see if the loop should continue happens at the end of the main loop code
  • accumulators: variables used to add up values
    • sum (initialize accumulator to 0)
    • product (initialize accumulator to 1)
  • break: causes a loop to end
  • continue: causes the loop to skip to the next iteration
  • priming read: a read of input data before a loop starts to determine whether the loop should execute at all; it is repeated right before the end of the loop

Examples

  • A "for" loop counting from 1 to 10: for (int i = 1; i <= 10; i++) { System.out.println(i); }
  • A "while" loop counting from 1 to 10: int i = 1; while (i <= 10) { System.out.println(i); i++; }
  • A "do/while" loop counting from 1 to 10: int i = 1; do { System.out.println(i); i++; } while (i <= 10);
  • A "for" loop summing the odd numbers between 10 and 20: int sum = 0; for (int i = 11; i <= 20; i = i + 2) { sum = sum + i; }
  • A "while" loop summing the odd numbers between 10 and 20: int sum = 0; int i = 11; while (i <= 20) { sum = sum + i; i = i + 2; }
  • A "do/while" loop summing the odd numbers between 10 and 20: int sum = 0; int i = 11; do { sum = sum + i; i = i + 2; } while (i <= 20);
  • A loop with a priming read that multiplies numbers entered until 0 is entered: java.util.Scanner kbd = new java.util.Scanner(System.in); int product = 1; System.out.print("Enter an integer (0 to end): "); int i = kbd.nextInt(); while (i != 0) { product = product * i; System.out.print("Enter another integer (0 to end): "); i = kbd.nextInt(); }
  • A "for" loop that displays all the command line arguments: for (String s : args) { System.out.println(s); }

Sample programs

Resources