C# while loop
In this chapter you will learn:
- What is while loop
- How to create syntax
- Example for while loop
- Use a while loop to calculate and display the Fibonacci numbers less than 50
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;// w w w . j a va2s.c o m
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/* ww w. j a v a 2 s . c o 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.
Next chapter...
What you will learn in the next chapter:
- What is do while loop
- How to create do while loop
- Example for do while loop
- Example to do calculation in a do while loop
- Using break to exit a do-while loop
- How to use do while loop to find the square root of a number
- Do / while loop with a console read