🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C Loops — for, while, do-while with Examples

C FundamentalsC Loops🟢 Free Lesson

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.

PartRole
InitializationRuns once before the loop starts
ConditionChecked before each iteration
UpdateRuns at the end of each iteration
BodyStatements 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.

LoopBest When
forIteration count is known
whileCondition alone controls repetition
do-whileBody 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

  1. Which loop form runs its body at least once even if the condition is false?
  2. What are the three clauses of a for loop and when does each run?
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement