Back

Activity 2.5 Iteration: While Loops

divider

Introduction

Activity 2.5

Iteration: While Loops

Topics

  • Doing Things Repeatedly
  • While Loops
  • Sentinel Values
  • Infinite Loops

Doing Things Repeatedly 🔁

Programs also often need to perform the same action multiple times. Think about counting, processing a list of items, or waiting for a specific event.

This concept of repeating a sequence of instructions is called iteration (or looping). It's essential for automating repetitive tasks.

Unlike selection (if statements), which chooses one path, iteration repeats a path until a condition is no longer met.

Iteration Sample

How can we repeat the "play next song" action for every song in the playlist?

Playlist Screenshot

The while Loop

The while loop is the simplest way to perform iteration in Java. It repeatedly executes a block of code as long as its condition remains true.

int timer = 10;
while (timer > 0) {
System.out.println(timer);
timer--;
}

Components of a While Loop

int timer = 10;
while (timer > 0) {
System.out.println(timer);
timer--;
}

1. (while) While keyword

2. (timer > 0) Condition

3. ({ }) Loop Body/Code Block: Must contain the repeated action and the updating statement that changes the condition.

Demo 1: Counting Up

int start = 1;
int end = 10;
while (start <= end) {
System.out.println(start);
start++;
}

Demo 2: Counting Powers of 2

int number = 2;
while (number <= 1024) {
System.out.println(number);
number *= 2;
}

The Sentinel Value

A sentinel value is a specific input or condition that signals the loop to stop.

  • It's used when the number of iterations is unknown beforehand.
  • It acts as a terminating signal (the 'stop sign' for the loop).
int score = 0;
while (score != -1) {
System.out.print("Enter a score (-1 to stop):");
score = input.nextInt();
// Remaining code omitted
}

In this example, -1 is the sentinel value that stops the loop.

Demo 3: Menu system

String choice = "";
while (choice != "2") {
System.out.println("-Menu-");
System.out.println("1) Place Order");
System.out.println("2) Finish");
System.out.print("-> ");
choice = input.nextLine();
// Remaining code omitted...
}

Infinite Loops

  • A major mistake is creating a loop that never stops. These are called infinite loops.
  • An infinite loop occurs when the loop's condition never becomes false. They cause your program to freeze or crash because they consume all available resources.
  • Prevent them by ensuring the code inside the loop modifies the variable(s) used in the condition.

Infinite Loops

int number = 1;
while (number <= 100) {
System.out.println(number);
}

Infinite Loops

int number = 1;
while (number <= 100) {
System.out.println(number);
number++;
}

Key Terms

Iteration / Looping
The process of repeatedly executing a set of instructions.
While Loop
A control structure that executes a block of code as long as a specified condition remains true.
Loop Condition
The boolean expression checked at the start of each iteration to determine if the loop should continue.

Key Terms

Sentinel Value
A special value or input that signals the end of the input or the stopping point for a loop with an unknown number of iterations.
Infinite Loop
A loop whose condition never becomes false, causing it to run indefinitely and crash the program.

'F' → Fullscreen

Objectives

  • icon Writing while loops
  • icon Using while loops to implement menu systems
divider

Activity Tasks

  • icon Create a new project named 2-5-Loops.
  • icon Complete each task individually.

Task 1: 99 Bottles Song

  • icon Pay attention to the condition. When do you stop singing the song?
Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - 99 Bottles Song ---\n");
System.out.print("Enter your favorite soda: ");
String soda = input.nextLine();
int bottles = 99;
// While there are bottles left to pass around...
while (bottles > 0) {
System.out.println(bottles + " bottles of " + soda + " on the wall,");
System.out.println(bottles + " bottles of " + soda + "!");
System.out.println("You take one down, pass it around,");
bottles--;
System.out.println(bottles + " bottles of " + soda + " on the wall!");
// Uncomment if you want to pause between iterations
// input.nextLine();
}
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
}
}
//

Task 2: Turn-Based Battle

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
23 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - 99 Bottles Song ---\n");
System.out.print("Enter your favorite soda: ");
String soda = input.nextLine();
int bottles = 99;
// While there are bottles left to pass around...
while (bottles > 0) {
System.out.println(bottles + " bottles of " + soda + " on the wall,");
System.out.println(bottles + " bottles of " + soda + "!");
System.out.println("You take one down, pass it around,");
bottles--;
System.out.println(bottles + " bottles of " + soda + " on the wall!");
// Uncomment if you want to pause between iterations
input.nextLine();
}
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Demo 2 - Turn-Based Battle ---\n");
int playerHealth = 10;
int enemyHealth = 6;
boolean fighting = true;
// Another suitable condition: playerHealth > 0 && enemyHealth == 0
while (fighting) {
System.out.println("Health: " + playerHealth);
System.out.println("Goblin: " + enemyHealth);
System.out.println("\n-Menu-");
System.out.println("1) Attack");
System.out.println("2) Heal");
System.out.print("-> ");
String choice = input.nextLine().toLowerCase();
if (choice.equals("1") || choice.equals("attack")) {
System.out.println("Player attacks!");
int playerAttack = (int)(Math.random() * 6); // 0 to 5
if (playerAttack > 0) {
System.out.println("You did " + playerAttack + " damage.");
enemyHealth = enemyHealth - playerAttack;
}
else {
System.out.println("Missed!");
}
}
else if (choice.equals("2") || choice.equals("heal")) {
int potion = (int)(Math.random() * 3) + 1; // 1 to 3
System.out.println("Healed " + potion + " points.");
playerHealth = playerHealth + potion;
}
else {
System.out.println("Invalid option. You lose your turn!");
}
if (enemyHealth > 0) {
System.out.println("Goblin attacks!");
int enemyAttack = (int)(Math.random() * 4); // 0 to 3
if (enemyAttack > 0) {
System.out.println("Goblin did " + enemyAttack + " damage.");
playerHealth = playerHealth - enemyAttack;
}
else {
System.out.println("Missed!");
}
}
else {
System.out.println("Goblin defeated!");
fighting = false; // Exit battle
}
if (playerHealth <= 0) {
System.out.println("You were defeated!");
fighting = false; // Exit battle
}
}
}
}
//
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1 - 99 Bottles Song ---
Enter your favorite soda: Code Zero
99 bottles of Code Zero on the wall,
99 bottles of Code Zero!
You take one down, pass it around,
98 bottles of Code Zero on the wall!
Press enter to continue... [Enter]
--- Demo 2 - Turn-Based Battle ---
Health: 10
Goblin: 6
-Menu-
1) Attack
2) Heal
-> 1
Player attacks!
You did 3 damage.
Goblin attacks!
Missed!
Health: 10
Goblin: 3
-Menu-
1) Attack
2) Heal
-> 1
Player attacks!
You did 4 damage.
Goblin defeated!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. When designing a while loop, you must ensure that the loop will eventually stop. In Task 1 (99 Bottles), the update was simple (bottles--). In Task 2 (Turn-Based Battle), how did the code inside the loop ensure the loop condition (while (fighting)) could eventually change to false?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete