Iteration and Recursion in C++
Understanding Iteration
The Power of Repetition
In programming, you'll often need to perform the same action multiple times. Instead of copying and pasting code, which is inefficient and error-prone, we use loops. A loop is a control structure that repeats a block of code as long as a specific condition is true. This process is called iteration.
C++ provides three primary tools for iteration: the for loop, the while loop, and the do-while loop. Each has a specific purpose, and choosing the right one makes your code cleaner and more effective.
Loops in C programming are used to repeat a block of code until the specified condition is met.
The For Loop
The for loop is your go-to choice when you know exactly how many times you want to repeat an action. Its syntax is designed to handle a counter that tracks the number of iterations.
A for loop has three parts in its parentheses, separated by semicolons:
- Initialization: A counter variable is declared and initialized. This part runs only once, at the very beginning.
- Condition: The loop continues to run as long as this condition evaluates to true. It's checked before each iteration.
- Increment/Decrement: This expression is executed after each iteration, usually to update the counter.
#include <iostream>
int main() {
// This loop prints numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
// ^ initialization
// ^ condition
// ^ increment
std::cout << i << std::endl;
}
return 0;
}
This structure keeps all the loop control logic neatly in one line, making the code easy to read. It's perfect for tasks like iterating through the elements of an array or a vector, where the number of elements is known.
Use a
forloop when you have a definite starting and ending point for your iterations.
The While Loop
What if you don't know how many times you need to loop? For situations where a loop should continue as long as a condition is true, we use the while loop. It checks its condition before executing the code inside.
If the condition is false from the start, the loop's body will never run. This makes it ideal for situations that depend on external input or a changing state within the program.
#include <iostream>
int main() {
int number = 0;
// Ask the user for a positive number
while (number <= 0) {
std::cout << "Enter a positive number: ";
std::cin >> number;
}
std::cout << "You entered: " << number << std::endl;
return 0;
}
In this example, the loop continues to prompt the user until they provide valid input. We can't predict how many attempts this will take, making the while loop the perfect tool.
The Do-While Loop
The do-while loop is a variation of the while loop with one crucial difference: it checks the condition after the loop's body has executed. This guarantees that the code inside the loop will run at least once, regardless of the condition.
This is useful for scenarios where an initial action is always necessary before checking whether to repeat it, such as displaying a menu of options to a user.
#include <iostream>
int main() {
char selection;
do {
std::cout << "MENU:\n";
std::cout << "1. Start Game\n";
std::cout << "2. Load Game\n";
std::cout << "Q. Quit\n";
std::cout << "Enter your selection: ";
std::cin >> selection;
// Process the selection here...
} while (selection != 'Q' && selection != 'q');
std::cout << "Goodbye!" << std::endl;
return 0;
}
The menu is always displayed at least once. After the user makes a selection, the condition checks if they chose to quit. If not, the loop runs again, displaying the menu once more.
| Loop Type | When to Use | Key Feature |
|---|---|---|
for | You know the number of iterations. | Initialization, condition, and increment are in one line. |
while | You don't know the number of iterations. | Condition is checked before each iteration. May not run at all. |
do-while | You need the loop to run at least once. | Condition is checked after each iteration. Always runs at least once. |
Best Practices
Writing good loops is about more than just syntax. It's about clarity and avoiding common mistakes.
- Avoid Infinite Loops: Always ensure your loop's condition will eventually become false. Forgetting to increment a counter in a
whileloop is a classic mistake. - Keep It Clear: Use meaningful variable names for your counters (e.g.,
rowIndexinstead ofi). The logic inside the loop should be easy to follow. - Scope Matters: Declare counter variables within the
forloop's initialization (for (int i = 0; ...)). This limits the variable's scope to the loop itself, preventing accidental use elsewhere.
Which type of loop is most appropriate when you know the exact number of times a block of code should be executed?
What is the primary difference between a while loop and a do-while loop?
Mastering iteration is a fundamental step in becoming a proficient programmer. By choosing the right loop for the job, you can write code that is both powerful and easy to understand.