Mastering C# While and Do‑While Loops: Syntax, Examples, and Best Practices
Mastering C# While and Do‑While Loops
Explore how to implement C# while and do…while loops, understand their differences, and learn best practices for writing clean, efficient code.
In software development, repetitive execution of a code block is common, whether for iterating over collections, handling user input, or performing calculations. While manual repetition is error‑prone and unreadable, loops provide a concise, scalable solution. This article delves into the two primary looping constructs in C#—while and do…while—and highlights their distinct behaviors.
C# while Loop
The while keyword initiates a loop that evaluates its condition before executing the body. Its syntax mirrors that of many modern languages:
while (testExpression)
{
// loop body
}
How the while Loop Works
- A boolean
testExpressionis evaluated. - If the expression is
true, the loop body runs, then the expression is re‑evaluated. - The loop terminates when the expression becomes
false.
While‑Loop Flowchart
Example 1: Basic while Loop
using System;
namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("C# While Loop: Iteration {0}", i);
i++;
}
}
}
}
Output:
C# While Loop: Iteration 1 C# While Loop: Iteration 2 C# While Loop: Iteration 3 C# While Loop: Iteration 4 C# While Loop: Iteration 5
The loop starts with i set to 1. It continues as long as i is less than or equal to 5, incrementing i each cycle. When i becomes 6, the condition fails and the loop exits.
Example 2: Summing the First Five Natural Numbers
using System;
namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1, sum = 0;
while (i <= 5)
{
sum += i;
i++;
}
Console.WriteLine("Sum = {0}", sum);
}
}
}
Output:
Sum = 15
In this example, the loop accumulates the value of i into sum until i exceeds 5. The final result is 15, confirming the well‑known formula for the sum of the first five natural numbers.
C# do…while Loop
The do…while construct is similar to while, but the condition is evaluated after the loop body runs. This guarantees that the body executes at least once, regardless of the initial condition.
do
{
// loop body
} while (testExpression);
How the do…while Loop Works
- The loop body executes first.
- The
testExpressionis evaluated. - If
true, the body repeats. - When
false, the loop terminates.
Do…While Flowchart
Example 3: Multiplication Table Using do…while
using System;
namespace Loop
{
class DoWhileLoop
{
public static void Main(string[] args)
{
int i = 1, n = 5, product;
do
{
product = n * i;
Console.WriteLine("{0} * {1} = {2}", n, i, product);
i++;
} while (i <= 10);
}
}
}
Output:
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50
The program prints the 5× table from 1 to 10. Notice that the loop body runs before checking i <= 10, ensuring all 10 iterations occur.
Infinite Loops in C#
When the loop condition never becomes false, the loop runs indefinitely. Such infinite loops are intentional in scenarios like event loops, game loops, or long‑running services.
Infinite while Loop
while (true)
{
// loop body
}
Infinite do…while Loop
do
{
// loop body
} while (true);
Use infinite loops sparingly and always provide a clear exit strategy (e.g., a break statement or an external condition) to prevent resource exhaustion.
C Language
- C# foreach Loops: Iterate Arrays and Collections with Ease
- C++ While and Do‑While Loops – Mastering Repetition in Your Code
- Mastering While and Do‑While Loops in C: Practical Examples
- Mastering Python's While Loop: Syntax, Examples, and Best Practices
- Mastering Python Loop Control: break & continue
- Mastering Java While & Do‑While Loops: Step‑by‑Step Tutorial
- Mastering Loop and Exit Constructs in VHDL: A Practical Guide
- Master C Loops: For, While, and Do‑While Explained with Practical Examples
- While vs. Do‑While Loops: Clear Comparison with Practical Examples
- Mastering WHILE Loops in SINUMERIK 840D CNC Programming