PHP Do-While Loops - Control Structures
Learning Objectives
- Master PHP loop structures
- Choose appropriate loop types
- Control loop execution flow
- Optimize loop performance
Introduction to PHP Do-While Loops
Welcome to our session on PHP Do-While Loops, a versatile control structure that ensures a block of code executes at least once before checking a condition. The do-while loop is a variation of the while loop with one critical difference: the condition is evaluated after the code block executes rather than before.
Think of a do-while loop as a restaurant where you're served a meal first, and only afterward are you asked if you want to continue ordering more food. You'll always get at least one meal, regardless of whether you decide to order more.
The do-while loop is particularly useful when you need to guarantee that a piece of code runs at least once, regardless of any conditions. It's the perfect choice for input validation, menu systems, and any scenario where an action must occur before you can evaluate whether to continue.
Basic Syntax of PHP Do-While Loops
The do-while loop in PHP follows this syntax pattern:
do {
// code to be executed
// update condition state
} while (condition);
- Code Block: The statements to be executed at least once
- Update Condition State: Code that affects the condition variable(s)
- Condition: An expression that evaluates to either true or false
Note the semicolon (;) after the condition – it's required and a common source of syntax errors if forgotten.
Think of the do-while loop as a game where you first take your turn, and only afterward check if you should continue playing. You're guaranteed at least one turn, no matter what.
Example: Basic Do-While Loop
<?php
// Print numbers from 1 to 5 using a do-while loop
$i = 1;
do {
echo "Number: $i <br>";
$i++;
} while ($i <= 5);
?>
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
This loop produces the same output as an equivalent while loop or for loop. The difference becomes apparent when the initial condition is false, as we'll see in the next section.
Do-While vs. While Loops
The key difference between do-while and while loops is when the condition is evaluated:
Let's illustrate this key difference with an example where the initial condition is false:
While Loop (Executes 0 times)
<?php
$i = 10;
while ($i < 5) {
echo "This will not be printed<br>";
$i++;
}
echo "Final value of i: $i";
?>
Output:
Final value of i: 10
Do-While Loop (Executes 1 time)
<?php
$i = 10;
do {
echo "This will be printed once<br>";
$i++;
} while ($i < 5);
echo "Final value of i: $i";
?>
Output:
This will be printed once Final value of i: 11
This example clearly shows that the do-while loop guarantees at least one execution, even when the condition is initially false. It's like entering a revolving door - you'll always go through at least one rotation, even if you decide not to continue after that.
Practical Applications
Menu Systems
Do-while loops are perfect for menu-driven programs where you want to display the menu at least once:
<?php
// Simple command-line menu system simulation
function displayMenu() {
echo "<br>===== MENU =====<br>";
echo "1. View Records<br>";
echo "2. Add Record<br>";
echo "3. Update Record<br>";
echo "4. Delete Record<br>";
echo "5. Exit<br>";
echo "================<br>";
echo "Enter your choice: ";
}
// Simulating user choices
$userChoices = [1, 3, 5];
$choiceIndex = 0;
// Menu processing
do {
displayMenu();
// Get user choice (simulated)
$choice = $userChoices[$choiceIndex];
$choiceIndex++;
echo "$choice<br>";
// Process the choice
switch ($choice) {
case 1:
echo "Viewing all records...<br>";
break;
case 2:
echo "Adding a new record...<br>";
break;
case 3:
echo "Updating an existing record...<br>";
break;
case 4:
echo "Deleting a record...<br>";
break;
case 5:
echo "Exiting the program...<br>";
break;
default:
echo "Invalid choice. Please try again.<br>";
}
} while ($choice != 5 && $choiceIndex < count($userChoices));
?>
Output:
===== MENU ===== 1. View Records 2. Add Record 3. Update Record 4. Delete Record 5. Exit ================ Enter your choice: 1 Viewing all records... ===== MENU ===== 1. View Records 2. Add Record 3. Update Record 4. Delete Record 5. Exit ================ Enter your choice: 3 Updating an existing record... ===== MENU ===== 1. View Records 2. Add Record 3. Update Record 4. Delete Record 5. Exit ================ Enter your choice: 5 Exiting the program...
This menu system guarantees that the menu is displayed at least once, and then continues displaying it until the user chooses to exit or we run out of simulated choices. It's like a restaurant server who always presents the menu first, then returns to take your order until you indicate you're finished.
Input Validation
Do-while loops are excellent for input validation, where you need to prompt the user at least once:
<?php
// Input validation example
function getUserInput($prompt, $validationFunction) {
// Simulate different user inputs
$simulatedInputs = ["", "invalid", "abc123", "valid_input"];
$inputIndex = 0;
do {
// Prompt the user
echo $prompt;
// Get input (simulated)
$input = $simulatedInputs[$inputIndex];
$inputIndex = min($inputIndex + 1, count($simulatedInputs) - 1);
echo "'$input'<br>";
// Validate the input
$isValid = $validationFunction($input);
if (!$isValid) {
echo "Invalid input. Please try again.<br>";
}
} while (!$isValid && $inputIndex < count($simulatedInputs));
return $input;
}
// Example: Username validation
$username = getUserInput("Enter username (alphanumeric, min 4 characters): ", function($input) {
return preg_match('/^[a-zA-Z0-9]{4,}$/', $input);
});
echo "Valid username received: $username";
?>
Output:
Enter username (alphanumeric, min 4 characters): '' Invalid input. Please try again. Enter username (alphanumeric, min 4 characters): 'invalid' Invalid input. Please try again. Enter username (alphanumeric, min 4 characters): 'abc123' Valid username received: abc123
This example shows how to use a do-while loop for input validation. It prompts for input at least once, then continues prompting until valid input is received or we run out of simulated inputs. It's like a form that always presents input fields, then shows error messages and prevents submission until all fields are valid.
Processing with Unknown Initial State
Do-while loops are useful when you need to process data but don't know the state before you begin:
<?php
// Processing a linked list (simulated)
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
// Create a linked list: 1 -> 3 -> 5 -> 7 -> 9
$head = new Node(1);
$head->next = new Node(3);
$head->next->next = new Node(5);
$head->next->next->next = new Node(7);
$head->next->next->next->next = new Node(9);
// Find a value in the linked list
function findInLinkedList($head, $targetValue) {
if ($head == null) {
return false;
}
$current = $head;
$position = 0;
do {
if ($current->data == $targetValue) {
echo "Found value $targetValue at position $position<br>";
return true;
}
$current = $current->next;
$position++;
} while ($current != null);
echo "Value $targetValue not found in the list<br>";
return false;
}
// Search for values
findInLinkedList($head, 5); // Should find at position 2
findInLinkedList($head, 8); // Should not find
?>
Output:
Found value 5 at position 2 Value 8 not found in the list
This example uses a do-while loop to traverse a linked list. We examine at least the first node, then continue as long as there are more nodes to check. It's like a detective who checks at least the first room of a building, then continues investigating if there are more rooms to explore.
Advanced Techniques
Emulating a Do-While Loop in HTML/JavaScript Forms
Understanding do-while loops in PHP helps when working with form validation in web applications:
<?php
// Form processing example
$formErrors = [];
// Simulate form submission
$isSubmitted = isset($_GET['simulate_submit']);
$simulatedInputs = [
'empty' => ['name' => '', 'email' => ''],
'invalid' => ['name' => 'John', 'email' => 'not-an-email'],
'valid' => ['name' => 'John Doe', 'email' => 'john@example.com']
];
// Which input set to use
$inputSet = isset($_GET['input_set']) ? $_GET['input_set'] : 'empty';
$_POST = $simulatedInputs[$inputSet];
// Process form on submission
if ($isSubmitted) {
// Validate name
if (empty($_POST['name'])) {
$formErrors['name'] = "Name is required";
}
// Validate email
if (empty($_POST['email'])) {
$formErrors['email'] = "Email is required";
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$formErrors['email'] = "Invalid email format";
}
// If no errors, process the form
if (empty($formErrors)) {
echo "Form processed successfully!<br>";
echo "Name: " . htmlspecialchars($_POST['name']) . "<br>";
echo "Email: " . htmlspecialchars($_POST['email']) . "<br>";
}
}
// Display form (this is similar to the 'do' part of a do-while loop)
echo "<h3>Contact Form</h3>";
echo "<form method='post'>";
// Name field
echo "<div>";
echo "Name: <input type='text' name='name' value='" . (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '') . "'>";
if (isset($formErrors['name'])) {
echo "<span style='color: red;'>" . $formErrors['name'] . "</span>";
}
echo "</div>";
// Email field
echo "<div>";
echo "Email: <input type='text' name='email' value='" . (isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '') . "'>";
if (isset($formErrors['email'])) {
echo "<span style='color: red;'>" . $formErrors['email'] . "</span>";
}
echo "</div>";
// Submit button
echo "<button type='submit'>Submit</button>";
echo "</form>";
// Simulation controls (not part of the actual example, just for demonstration)
echo "<hr>";
echo "<h4>Simulation Controls</h4>";
echo "<a href='?simulate_submit=1&input_set=empty'>Simulate Empty Submit</a> | ";
echo "<a href='?simulate_submit=1&input_set=invalid'>Simulate Invalid Submit</a> | ";
echo "<a href='?simulate_submit=1&input_set=valid'>Simulate Valid Submit</a>";
// The conditional check (similar to the 'while' part of a do-while loop)
// In a real application, this would be handled by the browser submitting the form again
?>
This example demonstrates how form processing in web applications follows a pattern similar to a do-while loop: the form is always displayed at least once (the 'do' part), and if there are validation errors, it is displayed again (the 'while' condition). It's like a customs officer who always checks your passport once, then continues checking if they find issues that need correction.
Note:
This example simulates form submission using GET parameters for demonstration. In a real application, you'd use proper POST submissions and more robust validation.
Using Break and Continue
Like other loops, do-while loops can use break and continue statements to control execution flow:
<?php
// Process a sequence until a certain condition is met
$data = [5, 10, 15, 0, 20, 25, 30];
$index = 0;
$sum = 0;
do {
$value = $data[$index];
$index++;
// Skip negative values
if ($value < 0) {
echo "Skipping negative value: $value<br>";
continue;
}
// Break if we find a zero
if ($value == 0) {
echo "Found a zero value, breaking the loop<br>";
break;
}
// Process the value
$sum += $value;
echo "Added $value to sum, new sum: $sum<br>";
} while ($index < count($data));
echo "Final sum: $sum";
?>
Output:
Added 5 to sum, new sum: 5 Added 10 to sum, new sum: 15 Added 15 to sum, new sum: 30 Found a zero value, breaking the loop Final sum: 30
This example demonstrates how break and continue statements can control the flow of a do-while loop. The continue statement skips the current iteration (though none of our values are negative), while the break statement exits the loop entirely when we find a zero. It's like a quality control inspector who examines each item on a production line – skipping certain types, processing others, and stopping the line if a critical issue is found.
Nested Do-While Loops
Like other loop types, do-while loops can be nested inside each other:
<?php
// Generate a simple pattern using nested do-while loops
$i = 1;
do {
$j = 1;
do {
echo "* ";
$j++;
} while ($j <= $i);
echo "<br>";
$i++;
} while ($i <= 5);
?>
Output:
* * * * * * * * * * * * * * *
This example uses nested do-while loops to create a pattern of asterisks. The outer loop controls the rows, while the inner loop controls the columns. It's like a building construction where you must complete at least one floor (outer loop), and on each floor, you must build at least one room (inner loop).
Performance Considerations
Performance considerations for do-while loops are similar to those for while loops:
- Condition evaluation: The condition is evaluated after each iteration, so keep it as simple as possible.
- Resource handling: Properly manage resources opened within the loop.
- Loop termination: Ensure there's a clear path for the loop to terminate to avoid infinite loops.
- Choose wisely: Use do-while only when you truly need at least one guaranteed execution.
Inefficient vs. Efficient Do-While Loop
Inefficient:
<?php
// Inefficient - complex condition evaluated each time
$i = 0;
do {
// Process something
echo "Processing item $i<br>";
$i++;
} while ($i < count($largeArray) && strtotime("now") < $endTime);
?>
Efficient:
<?php
// Efficient - pre-calculate array size
$i = 0;
$size = count($largeArray);
$timeLimit = $endTime;
do {
// Process something
echo "Processing item $i<br>";
$i++;
} while ($i < $size && time() < $timeLimit);
?>
The efficient version reduces repeated function calls in the condition, making each iteration faster. It's like preparing all your ingredients before cooking (mise en place) rather than measuring each ingredient every time you need it.
Real-World Examples
Command-Line Interface
Do-while loops are perfect for creating command-line interfaces:
<?php
// Command-line interface simulation
function processCommand($command) {
$parts = explode(' ', $command);
$action = strtolower(trim($parts[0]));
switch ($action) {
case 'list':
echo "Listing items...<br>";
echo "- Item 1<br>";
echo "- Item 2<br>";
echo "- Item 3<br>";
return true;
case 'add':
if (isset($parts[1])) {
$item = trim($parts[1]);
echo "Added item: $item<br>";
} else {
echo "Error: Item name required<br>";
}
return true;
case 'help':
echo "Available commands:<br>";
echo "- list: Show all items<br>";
echo "- add [item]: Add a new item<br>";
echo "- help: Show this help<br>";
echo "- exit: Exit the program<br>";
return true;
case 'exit':
echo "Exiting program...<br>";
return false;
default:
echo "Unknown command. Type 'help' for available commands.<br>";
return true;
}
}
// Simulate a series of commands
$commands = [
"help",
"list",
"add NewItem",
"unknown",
"exit"
];
$commandIndex = 0;
echo "Welcome to the Command Line Interface<br>";
echo "Type 'help' for available commands<br>";
do {
echo "<br>> ";
// Get command (simulated)
$command = $commands[$commandIndex];
echo "$command<br>";
$commandIndex++;
// Process the command
$continue = processCommand($command);
} while ($continue && $commandIndex < count($commands));
echo "Program terminated.";
?>
Output:
Welcome to the Command Line Interface Type 'help' for available commands > help Available commands: - list: Show all items - add [item]: Add a new item - help: Show this help - exit: Exit the program > list Listing items... - Item 1 - Item 2 - Item 3 > add NewItem Added item: NewItem > unknown Unknown command. Type 'help' for available commands. > exit Exiting program... Program terminated.
This example simulates a command-line interface using a do-while loop. It always shows the prompt at least once, and continues showing it until the user chooses to exit or we run out of simulated commands. It's like an interactive shell that always waits for at least one command, then continues accepting commands until told to stop.
Game Logic
Do-while loops are often used in game programming for main game loops:
<?php
// Simple text-based game simulation
class Player {
public $health = 100;
public $score = 0;
public function takeDamage($amount) {
$this->health -= $amount;
echo "Player takes $amount damage! Health: $this->health<br>";
}
public function scorePoints($amount) {
$this->score += $amount;
echo "Player scores $amount points! Score: $this->score<br>";
}
}
function generateEvent() {
$events = [
"Enemy attack" => function($player) {
$damage = rand(5, 20);
$player->takeDamage($damage);
},
"Find treasure" => function($player) {
$points = rand(10, 50);
$player->scorePoints($points);
},
"Health potion" => function($player) {
$healing = rand(10, 25);
$player->health += $healing;
echo "Player heals $healing health! Health: $player->health<br>";
}
];
$eventNames = array_keys($events);
$randomEvent = $eventNames[array_rand($eventNames)];
echo "<br>EVENT: $randomEvent<br>";
$events[$randomEvent];
return $events[$randomEvent];
}
// Game initialization
$player = new Player();
$turnCount = 0;
$maxTurns = 5;
echo "=== GAME START ===<br>";
// Main game loop
do {
$turnCount++;
echo "<br>--- TURN $turnCount ---<br>";
// Generate and handle a random event
$event = generateEvent();
$event($player);
// Check if player is defeated
if ($player->health <= 0) {
echo "<br>Player has been defeated!<br>";
break;
}
// Display current status
echo "Status: Health=$player->health, Score=$player->score<br>";
} while ($turnCount < $maxTurns);
echo "<br>=== GAME OVER ===<br>";
echo "Final Score: " . $player->score;
?>
Sample Output:
=== GAME START === --- TURN 1 --- EVENT: Find treasure Player scores 42 points! Score: 42 Status: Health=100, Score=42 --- TURN 2 --- EVENT: Enemy attack Player takes 15 damage! Health: 85 Status: Health=85, Score=42 --- TURN 3 --- EVENT: Health potion Player heals 22 health! Health: 107 Status: Health=107, Score=42 --- TURN 4 --- EVENT: Enemy attack Player takes 18 damage! Health: 89 Status: Health=89, Score=42 --- TURN 5 --- EVENT: Find treasure Player scores 23 points! Score: 65 Status: Health=89, Score=65 === GAME OVER === Final Score: 65
This example simulates a simple text-based game using a do-while loop for the main game loop. It guarantees at least one turn is played, and continues until the maximum number of turns is reached or the player is defeated. It's like a board game where you always get to take at least one turn, then continue playing until the game ends.
Common Patterns and Use Cases
The "At Least Once" Pattern
The most common pattern for do-while loops is processing data at least once before checking a condition:
<?php
// Process data from a potentially empty source
function processData($dataSource) {
$hasMoreData = true;
$result = [];
do {
// Get next chunk of data
$data = $dataSource->getNextChunk();
// Check if there's more data
$hasMoreData = !empty($data);
// Process the data if we have any
if ($hasMoreData) {
$result = array_merge($result, $data);
echo "Processed " . count($data) . " items<br>";
}
} while ($hasMoreData);
return $result;
}
// Simulated data source
class DataSource {
private $data = [
['id' => 1, 'name' => 'Item 1'],
['id' => 2, 'name' => 'Item 2'],
['id' => 3, 'name' => 'Item 3'],
];
private $position = 0;
private $chunkSize = 2;
public function getNextChunk() {
$chunk = [];
$remaining = min($this->chunkSize, count($this->data) - $this->position);
for ($i = 0; $i < $remaining; $i++) {
$chunk[] = $this->data[$this->position + $i];
}
$this->position += $remaining;
return $chunk;
}
}
// Use the function
$source = new DataSource();
$result = processData($source);
echo "Final result contains " . count($result) . " items.";
?>
Output:
Processed 2 items Processed 1 items Final result contains 3 items.
This pattern retrieves and processes at least one chunk of data before checking if there's more data available. It's like checking your mailbox – you always open it at least once to see if there's mail, then you stop checking once it's empty.
The "Validation" Pattern
Another common pattern is validating user input with feedback until valid input is received:
<?php
// Validate a password with specific requirements
function getValidPassword() {
// Simulated user inputs for demonstration
$attempts = [
"password", // Too simple
"Password", // No number
"Password1" // Valid
];
$attemptIndex = 0;
do {
// Get user input (simulated)
echo "Enter a password (min 8 chars, 1 uppercase, 1 number): ";
$password = $attempts[$attemptIndex];
echo "$password<br>";
$attemptIndex++;
// Validate requirements
$errors = [];
if (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters long";
}
if (!preg_match('/[A-Z]/', $password)) {
$errors[] = "Password must include at least one uppercase letter";
}
if (!preg_match('/[0-9]/', $password)) {
$errors[] = "Password must include at least one number";
}
// Display errors if any
if (!empty($errors)) {
echo "Invalid password:<br>";
foreach ($errors as $error) {
echo "- $error<br>";
}
}
} while (!empty($errors) && $attemptIndex < count($attempts));
if (empty($errors)) {
echo "Valid password accepted!<br>";
return $password;
} else {
echo "Too many invalid attempts<br>";
return false;
}
}
// Run the function
$password = getValidPassword();
if ($password) {
echo "Password set: " . str_repeat('*', strlen($password));
}
?>
Output:
Enter a password (min 8 chars, 1 uppercase, 1 number): password Invalid password: - Password must include at least one uppercase letter - Password must include at least one number Enter a password (min 8 chars, 1 uppercase, 1 number): Password Invalid password: - Password must include at least one number Enter a password (min 8 chars, 1 uppercase, 1 number): Password1 Valid password accepted! Password set: *********
This validation pattern prompts for input at least once, then continues prompting until valid input is received or the maximum number of attempts is reached. It's like a security checkpoint where you must show your ID at least once, and if there are issues with your ID, you'll be asked to provide alternative identification until acceptable credentials are presented.
Best Practices and Pitfalls
Best Practices
- Use for guaranteed execution: Choose do-while when you need to guarantee at least one execution of the loop body.
- Remember the semicolon: Always include the semicolon after the closing while condition - a common syntax error is forgetting this.
- Ensure termination: Make sure there's always a way for the loop to terminate by properly updating condition variables.
- Add safety limits: Consider adding maximum iteration counters to prevent infinite loops, especially with user input.
- Choose wisely: Only use do-while when its guaranteed-execution property is actually needed.
Common Pitfalls
Forgetting the Semicolon
One of the most common syntax errors with do-while loops is forgetting the semicolon after the condition:
<?php
// INCORRECT: Missing semicolon after condition
$i = 1;
do {
echo "Number: $i<br>";
$i++;
} while ($i <= 5) // Missing semicolon here
// CORRECT version:
$i = 1;
do {
echo "Number: $i<br>";
$i++;
} while ($i <= 5); // Semicolon included
?>
This is a unique aspect of do-while loops compared to other loop types in PHP - they require a semicolon after the condition.
Infinite Loops
Like all loops, do-while loops can become infinite if the condition never becomes false:
<?php
// INCORRECT: Condition never becomes false
$i = 1;
do {
echo "This will run forever: $i<br>";
$i = $i + 2; // $i will always be odd, never equal to 10
} while ($i != 10);
// CORRECT version:
$i = 1;
do {
echo "This will terminate: $i<br>";
$i++;
} while ($i <= 10);
?>
In the incorrect example, $i increases by 2 each time starting from 1, so it becomes 3, 5, 7, 9, 11, etc. - it will never equal 10, causing an infinite loop.
Using Do-While When While Would Be Better
Sometimes developers use do-while when a regular while loop would be more appropriate:
<?php
// LESS APPROPRIATE: Using do-while when condition should be checked first
$value = -5;
do {
echo "Processing value: $value<br>";
// Process the value...
$value++;
} while ($value > 0);
// MORE APPROPRIATE: Using while to check condition first
$value = -5;
while ($value > 0) {
echo "Processing value: $value<br>";
// Process the value...
$value++;
}
?>
Output of do-while:
Processing value: -5
Output of while:
(no output, since condition is false initially)
In this example, the do-while loop processes a negative value even though the condition specifies only positive values should be processed. The while loop correctly skips processing entirely.
Practice Exercises
Exercise 1: Simple Calculator
Create a simple calculator that performs operations and asks if the user wants to continue after each operation:
<?php
// Start with this code template
function performOperation($num1, $num2, $operator) {
// Implement the calculation logic
}
// Use a do-while loop to continue calculations until the user chooses to stop
?>
Hint:
Use a do-while loop that performs one calculation, shows the result, then asks if the user wants to continue. Use switch or if statements to handle different operations (+, -, *, /).
Exercise 2: PIN Validation
Create a PIN validation system that gives the user limited attempts to enter the correct PIN:
<?php
// Start with this code template
$correctPin = "1234";
$maxAttempts = 3;
// Use a do-while loop to allow multiple PIN entry attempts
?>
Hint:
Use a do-while loop that prompts for a PIN, checks if it's correct, and either grants access or tells the user how many attempts remain. Limit the total number of attempts.
Exercise 3: Interactive Quiz
Create a simple quiz game that asks questions until the user decides to quit or all questions have been asked:
<?php
// Start with this code template
$questions = [
["What is the capital of France?", "Paris"],
["Which planet is known as the Red Planet?", "Mars"],
["What is the largest mammal?", "Blue Whale"],
["How many sides does a hexagon have?", "6"]
];
// Use a do-while loop to present questions and keep score
?>
Hint:
Use a do-while loop to present at least one question. Keep track of the score and allow the user to continue or quit after each question. Display the final score when the quiz ends.
Homework Assignment
Create a program that uses different types of loops
Develop a PHP application that demonstrates the use of do-while loops in at least three different scenarios:
- Create a number guessing game where the computer picks a random number and the user has to guess it, with hints about whether the guess is too high or too low.
- Implement a menu-driven program that allows the user to select from various options (such as converting temperatures, calculating areas, or generating patterns).
- Develop a data validation system that ensures user input meets specific criteria (like password strength requirements or valid email formats).
Requirements:
- Include meaningful comments explaining your code.
- Implement at least one performance optimization technique discussed in class.
- Format your output with appropriate HTML and CSS.
- Each example should clearly demonstrate why a do-while loop is appropriate for that particular task.
- Submit your code via the class GitHub repository by the next session.