A while
loop in C# repeatedly executes a block of code as long as the specified condition is true
. Here's the basic syntax for a while
loop in C#:
main.cs49 chars5 lines
The condition
can be any expression that evaluates to a boolean value (true
or false
). The loop will continue to execute the code block as long as the condition is true
. Once the condition evaluates to false
, the loop will exit and the program will continue with the next line of code after the loop.
Here's a simple example of a while
loop that counts from 1 to 5:
main.cs66 chars8 lines
In this example, the condition
is i <= 5
, which means the loop will execute as long as the value of i
is less than or equal to 5. Inside the loop, we print the current value of i
and then increment i
by 1 using the i++
shorthand for i = i + 1
. The output of this code will be:
main.cs10 chars6 lines
gistlibby LogSnag