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

C# Loops — Complete Beginner Guide

C# FundamentalsLoops🟢 Free Lesson

C# Loops — Complete Beginner Guide

Learning Objectives

  • Repeat actions with for and while loops
  • Walk collections with foreach
  • Choose between while and do-while
  • Control flow with break and continue
  • Prevent infinite loops with safe patterns

Why Loops Exist

Loops run a block of code many times. Instead of copying the same line ten times, you write one line and tell C# how many times to repeat it. Loops power counters, searches, reports, and data processing.

The for Loop

A for loop has three parts: a starting value, a condition, and a step.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
PartRole
int i = 0Run variable created once
i less than 5Continue while true
i++Update after each pass

The loop prints zero through four, then stops when the condition fails.

Counting by steps

for (int i = 2; i <= 10; i += 2)
{
    Console.WriteLine(i);
}

This prints even numbers from two through ten.

The foreach Loop

foreach walks every item in a collection without managing an index yourself.

string[] names = { "Ana", "Ben", "Cy" };

foreach (string name in names)
{
    Console.WriteLine(name);
}

Use foreach when you need each element and do not need positional control. Use for when you need indexes or custom stepping.

The while Loop

while checks its condition before each run. If the condition starts false, the block never runs.

int count = 0;

while (count < 3)
{
    Console.WriteLine(count);
    count++;
}

while fits unknown iteration counts, such as reading input until a sentinel value arrives.

Guarding against infinite loops

Always update something the condition depends on. Forgetting the update keeps the condition true forever.

int remaining = 3;

while (remaining > 0)
{
    Console.WriteLine(remaining);
    remaining--;
}

The do-while Loop

do-while always runs the body at least once, then checks the condition.

int attempts = 0;

do
{
    attempts++;
    Console.WriteLine("Attempt " + attempts);
}
while (attempts < 2);

Use do-while when the first execution must happen before validation, such as prompting a user at least once.

while vs do-while

LoopChecks before body?Minimum runs
whileYesZero
do-whileNoOne

break and continue

break exits the nearest loop immediately. continue skips to the next iteration.

for (int i = 0; i < 10; i++)
{
    if (i == 3)
    {
        continue;
    }

    if (i == 7)
    {
        break;
    }

    Console.WriteLine(i);
}

The loop skips three, prints the rest up to six, then exits at seven.

Nested Loops

Loops can live inside loops. Use them for grids and tables.

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 3; col++)
    {
        Console.Write(row * col + " ");
    }

    Console.WriteLine();
}

Each outer pass runs the full inner loop. Keep nesting shallow while learning to stay readable.

Common Mistakes

Off by one errors

// Prints 0 through 4
for (int i = 0; i < 5; i++) { }

// Prints 1 through 5
for (int i = 1; i <= 5; i++) { }

Decide whether you want zero based or one based counting.

Changing the collection while looping

Modifying a list while foreach walks it can throw errors. Build a new list first, or use a standard for loop carefully.

Infinite while loops

If the condition never becomes false, the program hangs. Confirm that every pass moves toward the exit condition.

Key Takeaways

💡

  • for suits counted loops with a clear start, condition, and step
  • foreach is best for visiting every item in a collection
  • while checks first; do-while runs at least once
  • break exits a loop; continue jumps to the next pass
  • Always give every loop a clear path to termination

Practice Questions

  1. How many times does a basic for loop with i from zero to four run?
  2. Which loop is the simplest choice for printing every name in an array?
  3. What is the key difference between while and do-while?
  4. What does continue do compared with break?
  5. Write a loop that prints the numbers one through five, each on its own line.

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