A while loop in C# is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. The loop checks the condition before each iteration, and if the condition remains true, the loop continues executing the code. If the condition is false at any point, the loop exits and the program moves to the next statement after the loop.
Syntax:
while (condition)
{
// Code to execute as long as condition is true
}
Explanation:
condition: A boolean expression that is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.
Example: Print the value from 1 to 5
using System;
class ProgramExample
{
static void Main()
{
int number = 1; // Initialize the number variable
// While loop that runs until number is less than or equal to 5
while (number <= 5)
{
Console.WriteLine(number); // Prints the current value of number
number++; // Increment count after each iteration
}
}
}
Output:
1
2
3
4
5
2
3
4
5