C# While Loop
Loops through code while a condition is true.
C# While Loop
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The While Loop
The while loop loops through a block of code instructions as long as a specified condition is true.
while (condition)
{
// code block to be executed
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Examples
While Loop Example
Prints numbers 0 to 4.
using System;
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
}
}Do/While Loop
Executes at least once.
using System;
class Program
{
static void Main(string[] args)
{
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
}
}Loop with Condition
A simple countdown loop.
using System;
class Program
{
static void Main(string[] args)
{
int i = 10;
while (i > 0)
{
Console.WriteLine("Countdown: " + i);
i--;
}
Console.WriteLine("Liftoff!");
}
}Infinite Loop (Caution)
Be careful to update the loop variable!
using System;
class Program
{
static void Main()
{
int i = 0;
// This would run forever if condition is always true
// while(true) { ... }
while(i < 3)
{
Console.WriteLine("Safe Loop " + i);
i++;
}
}
}Do While User Input
Loops that depend on conditions.
using System;
class Program
{
static void Main()
{
// Conceptual example for interactive console
// In a real console, this would loop until user types 'exit' (not fully supported in this editor)
int i = 0;
do {
Console.WriteLine("Running...");
i++;
} while (i < 2);
}
}