C# while loop
Description
while loops repeatedly execute a body of code while a bool expression is true. The expression is tested before the body of the loop is executed.
Syntax
while loops take only one expression:
while(condition) {
statement(s);
}
Example
For example:
using System;//ww w.j a va2 s . c om
class Program{
static void Main(string[] args) {
int i = 5;
while (i > 0){
Console.WriteLine(i);
i--;
}
}
}
The output:
Example 2
Use a while loop to calculate and display the Fibonacci numbers less than 50.
class MainClass/*from ww w .j a v a 2 s . co m*/
{
public static void Main()
{
int oldNumber = 1;
int currentNumber = 1;
int nextNumber;
System.Console.Write(currentNumber + " ");
while (currentNumber < 50)
{
System.Console.Write(currentNumber + " ");
nextNumber = currentNumber + oldNumber;
oldNumber = currentNumber;
currentNumber = nextNumber;
}
}
}
The code above generates the following result.