The C# while statement continually executes a block of statements until a specified expression evaluates to false .
while (expression) statement
Like if statement the while statement evaluates the expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
int count = 1;
while (count < = 4)
{
MessageBox.Show("The value of i is : " + count);
count = count + 1;
}
The C# while statement executes a statement or a block of statements until a specified expression evaluates to false . The above program the loop will execute the code block 4 times.
You can implement an infinite loop using the while statement as follows:
while (true){
// statements
}
using System;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int count = 1;
while (count < = 4)
{
MessageBox.Show("The value of i is : " + count);
count = count + 1;
}
}
}
}
|