for, while, and Sentinel LoopsUnit 4 ยท Repetition and algorithms
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.
for loop changes the counter?Mastery task: Build a menu loop for a study tracker with options to add a session, view total minutes, or quit.