C# `while` Loop: Implementing Conditional Looping
Learn how to use `while` loops in C# for creating conditional loops that execute repeatedly as long as a specified condition is true. This tutorial covers basic `while` loop syntax, nested `while` loops, and provides examples demonstrating its application in various programming scenarios.
Understanding C#'s `while` Loop
The `while` loop in C# repeatedly executes a block of code as long as a specified condition is true. It's particularly useful when you don't know the exact number of iterations beforehand.
`while` Loop Syntax
while (condition) {
// Code to be executed repeatedly as long as the condition is true
}
The code within the curly braces `{}` will execute as long as the `condition` evaluates to `true`. If the condition is initially `false`, the loop body won't execute at all.
Example 1: Simple `while` Loop
This example prints numbers 1 through 10:
int i = 1;
while (i <= 10) {
Console.WriteLine(i);
i++;
}
Example 2: Nested `while` Loops
Nested `while` loops involve placing one `while` loop inside another. The inner loop executes completely for each iteration of the outer loop.
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
Console.WriteLine($"{i} {j}");
j++;
}
i++;
}
Example 3: Infinite `while` Loop
An infinite loop continues indefinitely unless explicitly terminated (e.g., using `break` or by pressing Ctrl+C in the console):
while (true) {
Console.WriteLine("This loop runs forever!");
}