Net-informations.com
SiteMap  | About    

How to use C# while loop

The while statement continually executes a block of statements until a specified expression evaluates to false . The expression is evaluated each time the loop is encountered and the evaluation result is true, the loop body statements are executed.

while(condition) { statement(s); }

c# while loop

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. A while loop can be terminated when a break, goto, return, or throw statement transfers control outside the loop. To pass control to the next iteration without exiting the loop, use the continue statement.

while(true)

An empty while-loop with this condition is by definition an infinite loop. 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;
            }
        }
    }
}

 CSharp Statements - Related Contents


 CSharp Statements - Related Programs