C# while loop

In this chapter you will learn:

  1. What is while loop
  2. How to create syntax
  3. Example for while loop
  4. 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:

  1. What is do while loop
  2. How to create do while loop
  3. Example for do while loop
  4. Example to do calculation in a do while loop
  5. Using break to exit a do-while loop
  6. How to use do while loop to find the square root of a number
  7. Do / while loop with a console read
Home »
  C# Tutorial »
    C# Language »
      C# Statements
C# Comments
C# if statement
C# while loop
C# do while loop
C# for loops
C# foreach statement
C# switch statement
C# break statement
C# continue statement
C# goto statement
C# XML Documentation