While loop will execute the block of statement until the specified condition evaluates true.
For loop is used in case, when we know how many times the block of statement will execute but in case if we don’t know the exact number of times the body will execute then while loop is best suited in that case.
Using keyword, while we create the body of while loop.
Syntax
while(condition)
{
//statement of body
}
Here, if condition evaluates true then only the block of statement will execute and condition will be checked again to execute the statement with in the while loop.
If condition evaluates false then while loop stops the execution of statement and programs comes out of loop.
Example
using System;
namespace whileLoop
{ class Program
{
static void Main(string[] args)
{
int i = 1;
while (i <= 4)
{
Console.WriteLine("i value: {0}", i);
i++;
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
While loop will execute the block of statement until the specified condition evaluates true.
For loop is used in case, when we know how many times the block of statement will execute but in case if we don’t know the exact number of times the body will execute then while loop is best suited in that case.
Using keyword, while we create the body of while loop.
Syntax
Here, if condition evaluates true then only the block of statement will execute and condition will be checked again to execute the statement with in the while loop.
If condition evaluates false then while loop stops the execution of statement and programs comes out of loop.
Example