while loop

In this chapter you will learn:

  1. Get to know while loop syntax
  2. 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:

  1. How to use do...while loop
  2. Using break to exit a do-while loop
  3. How to use do while loop to find the square root of a number
  4. Do / while loop with a console read
Home » C# Tutorial » Statements
Comments
if Statement
while loop
do...while loop
for loop
foreach
switch
break
continue statement
goto statement
Xml Documentation