C Loops — for, while, do-while with Examples
Learning Objectives
- Repeat code with for, while, and do-while loops
- Control loop counters and update expressions safely
- Use break and continue to adjust loop flow
- Diagnose and fix infinite loop mistakes
Why Loops Exist
Loops let you run a block of code many times without copying and pasting statements. Whenever you process a list of numbers, read multiple inputs, or repeat an action until a condition changes, a loop is the right tool. C gives you three primary loop forms, each suited to slightly different situations.
The for Loop
A for loop is best when you know in advance how many times you should run. It bundles initialization, condition, and update into one line so the loop control stays visible together.
for (int i = 1; i <= 5; i++) {
printf("Count: %d\n", i);
}
The loop starts with i set to one. Before every pass it checks whether i is at most five. After each pass it increments i. When the condition finally fails, the loop ends and execution continues after the closing brace.
| Part | Role |
|---|---|
| Initialization | Runs once before the loop starts |
| Condition | Checked before each iteration |
| Update | Runs at the end of each iteration |
| Body | Statements repeated while the condition holds |
You can count down as easily as up by starting high and decrementing until a lower bound. You can also skip values by changing the update step, such as adding two each time.
The while Loop
A while loop repeats as long as a condition remains true. Use it when the number of iterations is not known ahead of time, such as reading input until the user types a sentinel value or processing data until a file ends.
int attempts = 0;
while (attempts < 3) {
printf("Attempt number: %d\n", attempts + 1);
attempts++;
}
printf("Done trying.\n");
The condition is checked before each pass, so if it is false at the start the body never runs. Something inside the body must eventually move the condition toward false, or the loop never stops.
The do-while Loop
A do-while loop always runs its body at least once because the condition is tested at the bottom. This shape fits menus and confirm prompts where you want to display something before checking whether to continue.
int number;
do {
printf("Enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);
printf("You entered %d.\n", number);
Even if the user first enters an invalid value, the body executed once and the prompt appeared. The loop then repeats until a valid positive number arrives.
| Loop | Best When |
|---|---|
| for | Iteration count is known |
| while | Condition alone controls repetition |
| do-while | Body must run at least once |
break and continue
The break statement exits the innermost loop immediately. The continue statement skips the rest of the current iteration and jumps to the next condition check. Both are useful, but overuse can make loop logic hard to follow.
for (int i = 1; i <= 10; i++) {
if (i == 4) {
continue;
}
if (i == 8) {
break;
}
printf("%d ", i);
}
This loop prints values while skipping four and stopping before eight. Notice how break changes the overall flow while continue only affects one pass.
⚠️Infinite Loop Dangers
If the condition never becomes false, the program hangs. Common causes include a forgotten counter update, an off-by-one condition, or an update that moves the counter away from the goal. Always trace the counter on paper when a loop will not end.
Nested Loops
Loops can contain other loops. An outer loop controls rows while an inner loop controls columns, which is the standard pattern for printing grids, tables, and simple patterns of stars. Each inner loop finishes all of its passes for every single pass of the outer loop.
Keep nested loops shallow when possible. Deep nesting multiplies the number of executions quickly and can make performance drop faster than beginners expect.
Key Takeaways
💡
- Use for when the number of passes is known in advance
- Use while when a condition alone decides when to stop
- Use do-while when the body must execute at least once
- break exits a loop early, continue skips to the next iteration
- Missing updates cause infinite loops, so verify every counter change
Practice Questions
- Which loop form runs its body at least once even if the condition is false?
- What are the three clauses of a for loop and when does each run?
- How do break and continue differ in their effect on loop execution?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions