Loops
COP 3330 – Object Oriented Programming in Java: Loops
While Loop
Definition: The while loop is a control flow statement that allows code to be executed repeatedly based on a boolean condition.
Syntax:
The typical form of the while loop is:
java while (boolean expression) {stmt1; stmt2; stmt3; ... stmtk;}
Behavior:
First, evaluate the boolean expression.
If true, execute all statements within the loop block (from stmt1 to stmtk).
After execution, reevaluate the boolean expression to determine if the loop should continue.
If false goes pass to the end
Use Cases:
While loops are suitable for scenarios requiring repeated execution until a certain condition is met, such as gathering donations until a target is reached.
Good for when you know when you want to stop but dont know how many repetitions
Example Scenario:
Collecting donations until the total reaches $100:
java Scanner stdin = new Scanner(System.in); int money = 0; while (money < 100) { System.out.println("How much money will you donate?"); int donation = stdin.nextInt(); money += donation; }
Common Applications:
Typical usage includes menu-driven programs where users select an option repeatedly until they decide to quit.
Menu-Driven Program Structure Example
Main method framework for a user-driven program:
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
// Present menu choices via prints
int choice = stdin.nextInt();
while (choice != QUIT) {
if (choice == 1) {
// Execute choice 1
} else if (choice == 2) {
// Execute choice 2
} else {
// Print ERROR message: choice must be between 1 and QUIT.
}
// Present menu choices via prints.
choice = stdin.nextInt();
}
}
Included examples:
Donation Example
Bank Example (menu-driven program)
Half-life Example (calculating number of atoms over time)
Car Payment Example (calculating repayment schedule for a loan)
For Loop
Definition: The for loop is a control flow statement that provides a compact way to iterate a set of statements a fixed number of times.
Syntax:
General structure:
java for (init stmt; boolean expression; inc stmt) {}
Equivalent Layout: The for loop can be translated to a while loop:
{
init stmt;
while (boolean expression) {
stmt1;
stmt2;
stmt3;
...
stmtk;
inc stmt;
}
}
Execution Process:
Execute the initialization statement.
Evaluate the boolean expression; if true, execute the statements in the block.
Execute the increment statement.
Repeat from step 2.
Use Cases:
Suitable for iterating a specific number of times.
When you know how many times
Example Usage for Donations:
Gathering donations from a fixed number of participants:
java Scanner stdin = new Scanner(System.in); int money = 0; System.out.println("How many people will be donating?"); int numpeople = stdin.nextInt(); for (int i=0; i<numpeople; i++) { System.out.println("How much is donation #" + (i+1) + "?"); int donation = stdin.nextInt(); money += donation; }
Example for Calculating Exponents:
Scanner stdin = new Scanner(System.in);
System.out.println("Enter x.");
int x = stdin.nextInt();
System.out.println("Enter n.");
int n = stdin.nextInt();
int ans = 1;
for (int i=1; i<=n; i++) {
ans = ans * x;
}
System.out.println(x + " raised to the " + n + " equals " + ans);
Do-While Loop
Definition: A do-while loop is a control flow statement that executes statements at least once before evaluating the condition.
Syntax:
do {
stmt1;
stmt2;
stmt3;
...
stmtk;
} while (boolean expression);
Key Feature:
The boolean expression is evaluated at the end of the loop, ensuring that the loop body executes at least once. This is in contrast to while and for loops.
Guarantees at least 1 loop iteration
Example Usage in Menu-driven Program:
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int choice = 0;
do {
// Present menu choices via prints
choice = stdin.nextInt();
if (choice == 1) {
// Execute choice 1
} else if (choice == 2) {
// Execute choice 2
} else {
// Print ERROR message: choice must be between 1 and QUIT.
}
} while (choice != QUIT);
}
Example Bank Program Framework: Included as
Bank3.java.
Nested Loops
Definition: Nested loops allow a loop to be placed inside another loop, enabling more complex iteration behaviors.
Example 1 - Multiplication Table:
for (int row_num = 1; row_num <= rows; row_num++) {
for (int col_num = 1; col_num <= rows; col_num++) {
System.out.print("\t" + (row_num * col_num));
}
System.out.println();
}
Outer loop iterates through rows.
Inner loop prints entries based on the row and column numbers.
Example 2 - Triangle of Stars:
for (int linecnt = 1; linecnt <= numstars; linecnt++) {
for (int starcnt = 1; starcnt <= linecnt; starcnt++) {
System.out.print("*");
}
System.out.println();
}
The outer loop increments the line count, and the inner loop prints a varying number of stars per line.
Loop Control Statements
Break Statement
Definition: The break statement allows for an immediate exit from the loop, bypassing the normal boolean evaluation.
Use Case Example:
Checking if a number is prime:
java boolean isPrime = true; for (int i=2; i*i<=n; i++) { if (n % i == 0) { isPrime = false; break; } }
Continue Statement
Definition: The continue statement skips to the next iteration of the loop, effectively ignoring the remaining code for that iteration.
loop {
stmt a
if()
continue
stmt b
}Use Case Example:
Calculating the average of valid test scores:
java for (int i=0; i<n; i++) { System.out.println("Enter the next score."); int score = stdin.nextInt(); if (score < 0 || score > 100) { System.out.println("Sorry not in range, so not counted."); continue; } sum += score; valid++; }The loop processes valid scores while skipping invalid inputs using continue, promoting efficiency in score accumulation.