Summary of Iteration
Overview
In this chapter, we have explored three different types of loops in C: while loops, for loops, and do-while loops. Each type of loop serves different purposes, though some are more commonly used than others in practice.
The Three Types of Loops
While Loops
While loops are used when you need to repeat code but don't know in advance how many times the loop will execute. The loop continues as long as a condition remains true.
Syntax:
while (condition) {
// code to repeat
// make sure something here changes the condition
// or you'll have an infinite loop!
}
Best used for:
- Reading user input until a some specific value is entered
- Data validation loops
- Any situation where the number of iterations is unknown
Example from our sum program:
while (number != 0) {
total += number;
number = getNumber();
}
For Loops
For loops are used when you know exactly how many times you want to repeat something. They are perfect for counting operations.
Syntax:
for (initialization; condition; update) {
// code to repeat
}
Best used for:
- Drawing patterns (like our line of stars)
- Processing a known number of items
- Any counting operation
Example from our line drawing program:
for (i = 0; i < numStars; i++) {
printf("*");
}
When you want a loop to run exactly n times, use this pattern:
int i;
for (i = 0; i < n; i++) {
// loop body
}
Starting from 0 is the standard practice and will be important when we learn about arrays.
Do-While Loops
Do-while loops execute the loop body at least once before checking the condition. The condition is checked at the end of each iteration.
Syntax:
do {
// code to repeat
} while (condition);
Do-while loops are generally NOT recommended and are included here only for completeness. They are rarely used in practice for several reasons:
- The condition is buried at the bottom, making it harder to see when the loop will end
- They often require additional logic to handle error messages properly
- While loops can accomplish the same tasks more clearly
- Some modern languages (like Python) don't even include do-while constructs
Avoid using do-while loops in your own code. Use while loops instead.
Converting Between Loop Types
For Loop to While Loop
Any for loop can be converted to a while loop by separating out the three components:
For loop:
for (i = 0; i < numStars; i++) {
printf("*");
}
Equivalent while loop:
int i = 0; // initialization before the loop
while (i < numStars) { // condition in the while statement
printf("*");
i++; // update at the end of the loop body
}
The while loop version is more verbose but sometimes easier to understand when you're learning. However, when you're clearly counting, the for loop is preferred because it keeps all the loop control in one place.
While Loop to For Loop
While loops that involve counting can often be converted to for loops, but this isn't always appropriate. If the loop's purpose is not primarily about counting, stick with the while loop.
Choosing the Right Loop
Situation | Recommended Loop | Why |
---|---|---|
Known number of iterations | for | Keeps all loop control visible in one place |
Unknown number of iterations | while | More flexible, condition is clearly visible |
Must execute at least once | while with proper setup | Clearer than do-while, easier to handle error cases |
Counting operations | for | Standard practice, most readable |
Input validation | while | Can handle error messages cleanly |
Common Patterns
Common patterns are ways to patterns to the way we might write a piece of code. While the exact things we do may be different, there are patterns that we can use in our programs and simply modify to fit our needs
Input validation
// Get initial input prompt and read
printf("Enter a number (1-10): ");
scanf("%d", &num);
// Keep asking until valid
while (num < 1 || num > 10) {
//print error
printf("Error: Number must be between 1 and 10.\n");
//prompt and read again
printf("Enter a number (1-10): ");
scanf("%d", &num);
}
Counting Pattern
// Standard counting from 0 to n-1
for (i = 0; i < n; i++) {
// do something n times
}
Sentinel-Controlled Pattern
// Read until a particular value (the sentinel) is entered. In this example
// the sentinel is 0. When it is entered, the program stops
value = getInput();
while (value != 0) {
processValue(value);
value = getInput();
}
Key Takeaways
- For loops are best for counting and known iterations
- While loops are best for unknown iterations and validation
- Do-while loops should be avoided in favor of while loops
- Any for loop can be converted to a while loop
- Choose the loop type that makes your intent clearest
- Always ensure your loop will eventually terminate
- Keep loop control variables and logic as simple as possible
The goal is to write code that clearly expresses your intent. If you're counting, use a for loop. If you're waiting for a condition, use a while loop. When in doubt, while loops are generally the safer choice.