Iteration Types
Overview
In this chapter, we will explore 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 a code 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:
- Any situation where the number of iterations is unknown
- Reading user input until a some specific value is entered
- Data validation loops
Example:
read a number until a 0 value is read, summing up all entered values
int number;
int total = 0;
printf("Enter a number (0 to stop: ");
scanf("%d", &number);
while (number != 0) {
total += number;
printf("Enter a number (0 to stop: ");
scanf("%d", &number);
}
For Loops
For loops are used when you know 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
- Processing a known number of items
- Anything where the processing involves counting and number patterns
Example draw stars;
int numStars
printf("Enter a number of stars to draw: ");
scanf("%d", &numStars);
//loop runs numStar times printing one single * each time
for (i = 0; i < numStars; i++) {
printf("*");
}
printf("\n");
When you want a loop to run exactly n times, use this pattern:
int i;
for (i = 0; i < n; i++) {
// loop body
}
While it may seem odd to count from 0, this is actually 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);
While loops are generally the preferred to do-whiles. Do-whiles 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 when reading the code.
- They often require additional logic to handle edge cases
- While loops can accomplish the same tasks more clearly
- Some modern languages (like Python) don't even include do-while constructs
Use whiles over do-whiles for most situations
Best used for:
- interactive input error checking.
- For all other situations use while loops
Example:
//first run is truthy when it is the first run of the loop
int firstRun = 1;
do{
//when testing for something that is truthy or falsey, we should
//always test against 0. This is because 0 is the only false value
//while every non-zero is true. It is far safer to make it a habit
//to test against 0 or not 0.
if(firstRun != 0){
//print error message
printf("Error: Number of stars must be between 0 and 50 inclusive.");
//update firstRun variable
firstRun = 0;
}
//prompt and read
printf("Please enter number of stars on the line: ");
scanf("%d", &numStars);
}while(numStars < 0 || numStars > 50);
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:
int i;
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 and makes the counting clear.
When you write a a for loop there is always some counter you use for iteration. For example in this code, i is your loop counter:
for (i = 0; i < numStars; i++){
...
}
You should avoid modifying i outside of the for statement.
for (i = 0; i < numStars; i++){
...
// THIS IS BAD!!! You are changing i outside of the for() statement above
if(some condition){
i = numStars;
}
...
}
Instead you should add that condition for the loop expression instead. If there are many such modifications, a while loop is more appropriate.
for (i = 0; !(some condition) && i < numStars; i++){
...
}
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.