Tutorial 1: for, while, and Sentinel Loops

Unit 4 ยท Repetition and algorithms

Objectives

Use for when the loop has a clear counter or range. Use while when repetition depends on a condition. A sentinel is a special input value that ends a loop but is not processed as normal data.

Scanner input = new Scanner(System.in);
int total = 0;
int value;
do {
    System.out.print("Enter a mark (-1 to stop): ");
    value = input.nextInt();
    if (value >= 0) total += value;
} while (value != -1);

Write down the loop invariant: here, total is the sum of all valid marks entered so far. A clear invariant makes correctness easier to check.

Practice

  1. Print even numbers from 2 through 20.
  2. Read numbers until zero and report count, sum, and average.
  3. Trace a nested loop that prints a multiplication table.

Self-check

  1. Which part of a for loop changes the counter?
  2. Why can a sentinel not be included in the total?
  3. What input causes an infinite loop if the update is missing?

Mastery task: Build a menu loop for a study tracker with options to add a session, view total minutes, or quit.