Week 4: Automating Tasks with Loops
Learn how to use `for`, `while`, and `do...while` loops to execute code repeatedly in C++.
Explore Chapter 4Chapter 4: Repeating Actions with Loops
`for` Loops: Iterating a Specific Number of Times.
The `for` loop is commonly used when you know in advance how many times you want to repeat a block of code or when iterating over a range.
Classic `for` Loop Syntax
for (initialization; condition; update) {
// Code block to be executed
statement1;
statement2;
// ...
}
- initialization: Executed once before the loop starts. Often used to declare and initialize a loop counter (e.g., `int i = 0`).
- condition: Evaluated before each iteration. If it's `true`, the loop body executes. If it's `false`, the loop terminates.
- update: Executed at the end of each iteration, typically used to increment or decrement the loop counter (e.g., `i++`, `i--`).
Example: Counting 0 to 4
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
std::cout << "The number is " << i << std::endl;
}
return 0;
}
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Range-based `for` Loop (C++11 and later)
Modern C++ offers a simpler syntax for iterating over elements of a container (like arrays or vectors, which we'll cover later).
// Example with an array (Week 6 topic)
int numbers[] = {10, 20, 30};
for (int num : numbers) {
std::cout << num << " "; // Output: 10 20 30
}
std::cout << std::endl;
`while` Loops: Repeating Based on a Condition.
A `while` loop executes a block of code repeatedly as long as a specified condition remains `true`. The condition is checked before each iteration.
Syntax
while (condition) {
// Code to execute as long as condition is true
statement1;
// IMPORTANT: Ensure the condition eventually becomes false!
}
- If the condition is initially false, the loop body never executes.
- You must include logic within the loop to eventually make the condition false, otherwise, you'll create an infinite loop.
Example: Countdown
#include <iostream>
int main() {
int count = 3;
while (count > 0) {
std::cout << count << "..." << std::endl;
count--; // Decrement count, crucial to eventually exit
}
std::cout << "Blast off!" << std::endl;
return 0;
}
Output:
3...
2...
1...
Blast off!
`do...while` Loops: Condition Checked After Execution.
The `do...while` loop is similar to `while`, but the condition is checked after the loop body executes. This guarantees that the loop body will run at least once, even if the condition is initially false.
Syntax
do {
// Code to execute
// This block runs at least once
statement1;
// Ensure condition might eventually become false
} while (condition); // Note the semicolon at the end
Example: Simple Menu
#include <iostream>
int main() {
int choice;
do {
std::cout << "--- Menu ---\n";
std::cout << "1. Option 1\n";
std::cout << "2. Option 2\n";
std::cout << "0. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
// Process choice here (omitted for brevity)
if (choice != 0) {
std::cout << "Processing choice " << choice << "...\n";
}
} while (choice != 0); // Loop continues until user enters 0
std::cout << "Exiting menu." << std::endl;
return 0;
}
`do...while` is less common than `for` or `while`, but useful when you need to guarantee at least one execution of the loop body, like in menu-driven programs.
`break` and `continue`: Controlling Loop Flow.
These statements allow you to alter the normal execution flow within loops (`for`, `while`, `do...while`).
`break` Statement
The `break` statement immediately terminates the innermost loop it's contained within. Program execution continues with the statement immediately following the terminated loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
std::cout << "Found 5! Breaking loop." << std::endl;
break; // Exit the loop immediately
}
std::cout << "Current number: " << i << std::endl;
}
std::cout << "Loop finished." << std::endl;
Output:
Current number: 0
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5! Breaking loop.
Loop finished.
`continue` Statement
The `continue` statement skips the rest of the current iteration of the loop and proceeds immediately to the next iteration's condition check (`while`, `do...while`) or update expression (`for`).
for (int i = 1; i <= 5; i++) {
if (i % 2 != 0) { // If the number is odd
continue; // Skip the rest of this iteration
}
// This line only runs for even numbers
std::cout << "Found an even number: " << i << std::endl;
}
Output:
Found an even number: 2
Found an even number: 4
Nested Loops: Loops Inside Loops.
You can place one loop inside another. The inner loop will complete all its iterations for each single iteration of the outer loop.
Example: Creating a Grid Pattern
#include <iostream>
int main() {
int rows = 3;
int cols = 4;
for (int i = 0; i < rows; ++i) { // Outer loop (for rows)
for (int j = 0; j < cols; ++j) { // Inner loop (for columns)
std::cout << "(" << i << "," << j << ") "; // Print coordinate
}
std::cout << std::endl; // Newline after each row
}
return 0;
}
Output:
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)
Nested loops are common for working with multi-dimensional data structures (like 2D arrays or matrices) or when performing operations that require iterating through combinations of elements.