By 22/07/2015 27 Comments

C# While Loop

  • while loop also used for repeat the statements or expressions like for loop.
  • This loop mostly used to read the information from databases.
  • By using while loop, a programmer does not know that how many times this loop will be executed.
  • while loop is much simpler in its syntax than for loop.
  • While loop has only one part which is a boolean condition, when it executed, first it checks its condition, when it becomes true than the statement or expression inside while loop’s body will be performed or executed and if that condition becomes false than while loop will not be executed, bypassed by compiler and execution will go to next code (if available).

Syntax:

While (condition)
{
   Statement(s)
}

STATEMENT DESCRIPTION
While (condition) while keyword indicates its declaration, where (condition) is a boolean expression such as (number <= 10).
{ This parenthesis indicates the starting scope or body of while loop, inside this scope you can specify any multiple statements, expression or anything which do you want to be repeated by while loop. NOTE: This parenthesis is an optional, if you do not specify it than only single statement or expression will be repeated by while loop, but if you want to repeat more than one statements or expressions than you must specify these parenthesis. This is also called starting scope of while loop.
Statement(s) This can be anything to be repeated by while loop, mostly in while loops it can be information from databases.
} Closing scope of while loop.

Example:

using System;
namespace csharpBasic
{
    // Start class definition / declaration.
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            // Initialize an int type variable with 1.
            int count = 1;

            while (count <= 5)
            {   // Starting a while loop scope.

                // Print count variabvle.
                Console.WriteLine("Count : {0}",count);
                
                // Update count variable by 1.
                count++;

            }   // End of while loop scope.

            Console.ReadKey();

        } // End of main method definition. 
    } // End of class. 

    /*
   The Output will be:
    Count : 1
    Count : 2
    Count : 3
    Count : 4
    Count : 5
  */
}





Next Tutorial →


← Previous Tutorial


Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .