Sure! A while
loop in C# is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. Here's how it works in simple language:
Initialization: You start by initializing any variables that are needed for the condition inside the parentheses after the while
keyword.
Condition Checking: The condition inside the parentheses is evaluated. If it's true, the code inside the loop executes. If it's false, the loop terminates, and the program continues executing the code after the loop.
Loop Body: Inside the loop, you write the code that you want to execute repeatedly. This code will keep running as long as the condition remains true.
Update: Within the loop body, you typically modify the variables that are involved in the condition. This ensures that the condition eventually becomes false, terminating the loop.
Here's a simple example to illustrate a while
loop:
Example
using System;
class Program
{
static void Main()
{
int count = 0; // Initialization
while (count < 5) // Condition Checking
{
Console.WriteLine("Count is: " + count); // Loop Body
count++; // Update
}
Console.WriteLine("Loop finished.");
}
}
In this example:
count
with a value of 0
.while
loop checks whether count
is less than 5
.count
is less than 5
, it prints the current value of count
and increments count
by 1
.count
is no longer less than 5
.count
is 5
), the loop terminates, and "Loop finished." is printed.So, when you run this program, it will print:
Example
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop finished.