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);
}
| Part | Role |
|---|---|
| int i = 0 | Run variable created once |
| i less than 5 | Continue 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
| Loop | Checks before body? | Minimum runs |
|---|---|---|
| while | Yes | Zero |
| do-while | No | One |
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
- How many times does a basic for loop with i from zero to four run?
- Which loop is the simplest choice for printing every name in an array?
- What is the key difference between while and do-while?
- What does continue do compared with break?
- 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
- 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