while loop
In this chapter you will learn:
- Get to know while loop syntax
- Use a while loop to calculate and display the Fibonacci numbers less than 50
while loop syntax
while
loop statement uses a bool value to control a loop body.
The while
loop has the following form.
while(bool expression){
loop body
}
using System;/*from ja v a 2 s.com*/
class Program{
static void Main(string[] args) {
int i = 5;
while (i > 0){
Console.WriteLine(i);
i--;
}
}
}
The output:
Calculate with while loop
class MainClass/*ja v a 2 s .com*/
{
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:
- How to use 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