Java Iteration Structures and Control Flow Mechanisms
The while statement executes a block of code repeatedly as long as a specified boolean condition evaluates to true. Its execution flow is condition-first, meaning the body may never run if the initial state is false.
while (condition) {
// statements to execute repeatedly
}
Example: Sentinel-Controlled Validation
Scanner scanner = new Scanner(System.in);
System.out.print("Is the submission approved (y/n)? ");
String response = scanner.nextLine();
while (!"y".equalsIgnoreCase(response)) {
System.out.println("Reviewing documentation and practicing syntax...");
System.out.print("Re-evaluate submission (y/n)? ");
response = scanner.nextLine();
}
The do-while construct guarantees at least one execution because the condition is evaluated after the block. This is useful for menus or scenarios requiring initial user interaction.
do {
// statements
} while (condition);
Example: Post-Test Iteration
int iterationCounter = 1;
do {
System.out.println("Processing task #" + iterationCounter);
iterationCounter++;
} while (iterationCounter <= 5);
The for loop consolidates initialization, termination condition, and increment/decrement operations into a single header. It is ideal for counter-driven iterations where the number of cycles is known beforehand.
for (initialization; condition; update) {
// body
}
Example: Accumulating Values Over a Fixed Range
Scanner input = new Scanner(System.in);
double totalScore = 0.0;
int courseCount = 5;
for (int idx = 0; idx < courseCount; idx++) {
System.out.print("Enter score for module " + (idx + 1) + ": ");
totalScore += input.nextDouble();
}
System.out.printf("Average grade: %.2f%n", totalScore / courseCount);
Branching and Control Transfer
Control transfer keywords alter the standard sequential execution of loops. These are typically paired with conditional logic.
break: Immediate terminates the innermost enclosing loop or switch statement.continue: Skips the remainnig statements in the current iteration and jumps to the next cycle evaluation.
Example: Authentication Attempt Limiter
Scanner kb = new Scanner(System.in);
String validUser = "sysadmin";
String validPass = "securePass99!";
for (int attempts = 1; attempts <= 3; attempts++) {
System.out.print("Username: ");
String enteredUser = kb.next();
System.out.print("Password: ");
String enteredPass = kb.next();
if (enteredUser.equals(validUser) && enteredPass.equals(validPass)) {
System.out.println("Authentication successful.");
break;
}
int remaining = 3 - attempts;
if (remaining > 0) {
System.out.println("Invalid credentials. " + remaining + " attempts left.");
} else {
System.out.println("Account locked after maximum retries.");
}
}
Numeric Type Conversion
Java handles numeric type promotion automatically from lower to higher precision: byte → char → short → int → long → float → double. Downcasting requires explicit syntax (targetType) value to truncate or adjust precision, which may lead to data loss if not handled carefully.
Aplied Programming Exercises
Exercise 1: Range Summation Across Loop Variants Calculate the cumulative total of integers from 1 through 100 using each iteration type.
public class SummationExamples {
public static void main(String[] args) {
int boundary = 100;
int accumulator = 0;
// While approach
int pointer = 1;
while (pointer <= boundary) {
accumulator += pointer++;
}
System.out.println("While total: " + accumulator);
// Do-while approach
accumulator = 0;
pointer = 1;
do {
accumulator += pointer;
pointer++;
} while (pointer <= boundary);
System.out.println("Do-while total: " + accumulator);
// For approach
accumulator = 0;
for (int step = 1; step <= boundary; step++) {
accumulator += step;
}
System.out.println("For total: " + accumulator);
}
}
Exercise 2: Weekly Time Tracking Collect daily study durations for weekdays and compute the mean value.
import java.util.Scanner;
public class WeeklyTracker {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double weeklyTotal = 0;
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
for (String day : days) {
System.out.printf("Hours studied on %s: ", day);
weeklyTotal += reader.nextDouble();
}
System.out.println("Weekly average: " + (weeklyTotal / days.length) + " hours");
}
}
Exercise 3: Divisibility Pattern Generator Iterate 1 to 100. Output specific tokens based on modulo arithmetic for 3 and 5.
public class PatternSequence {
public static void main(String[] args) {
for (int num = 1; num <= 100; num++) {
boolean mod3 = (num % 3 == 0);
boolean mod5 = (num % 5 == 0);
if (mod3 && mod5) {
System.out.println("FlipFlop");
} else if (mod3) {
System.out.println("Flip");
} else if (mod5) {
System.out.println("Flop");
} else {
System.out.println(num);
}
}
}
}
Exercise 4: Factorial Computation with Validation Accept an integer between 1 and 10, then compute its factorial product. Reject out-of-bounds input.
import java.util.Scanner;
public class FactorialCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter integer (1-10): ");
if (input.hasNextInt()) {
int target = input.nextInt();
if (target < 1 || target > 10) {
System.out.println("Invalid range provided.");
} else {
long result = 1;
System.out.print(target + "! = ");
for (int i = 1; i <= target; i++) {
result *= i;
System.out.print(i + (i == target ? " = " : " * "));
}
System.out.println(result);
}
}
}
}
Exercise 5: Demographic Distribution Analysis Process 10 customer ages, categorize them by a 30-year threshold, and output percentages.
import java.util.Scanner;
public class CustomerDemographics {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int youngCount = 0, seniorCount = 0, validEntries = 0;
for (int i = 1; i <= 10; i++) {
System.out.printf("Age for visitor #%d: ", i);
int age = kb.nextInt();
if (age > 0) {
if (age < 30) youngCount++;
else seniorCount++;
validEntries++;
}
}
if (validEntries > 0) {
System.out.printf("Under 30: %.1f%%%n", (youngCount * 100.0) / validEntries);
System.out.printf("30 or older: %.1f%%%n", (seniorCount * 100.0) / validEntries);
}
}
}
Exercise 6: Sentinel-Based Transaction Terminal Recreate the checkout logic using a post-test loop structure.
import java.util.Scanner;
public class PointOfSale {
public static void main(String[] args) {
Scanner terminal = new Scanner(System.in);
double cartTotal = 0.0;
int itemCount = 0;
double itemPrice;
do {
System.out.print("Scan item price (0 to finish): ");
itemPrice = terminal.nextDouble();
if (itemPrice > 0) {
cartTotal += itemPrice;
itemCount++;
}
} while (itemPrice != 0);
System.out.printf("Items scanned: %d | Final total: $%.2f%n", itemCount, cartTotal);
}
}
Exercise 7: Brute-Force Equation Solver Solve the classic poultry/rabbit puzzle using iteration to match head and leg constraints.
public class AlgebraSolver {
public static void main(String[] args) {
int targetHeads = 35;
int targetLegs = 94;
for (int chickens = 0; chickens <= targetHeads; chickens++) {
int rabbits = targetHeads - chickens;
if ((chickens * 2) + (rabbits * 4) == targetLegs) {
System.out.println("Solution found: " + chickens + " chickens, " + rabbits + " rabbits.");
break;
}
}
}
}