C#: The while statement

Following the if else, the next common conditional statement should be the while statement.

In many ocassions, you may want to perform an action several times in a row. In other words, you have a block of code that you want executed repeatedly.

You can perform that using repeated line of of code or you can use a while statement.

The sytax for while statement is:

While (expression)
{
   statement 1;
   statement 2;
}

Similar to if else statement, the expression should resolve to true for the statements to be executed.

The While Statement
using System;

namespace Conditional
{
    class Program
    {
        private int number;

        private Program(int number1)
        {
            number = number1;
        }

        private void checkNumber()
        {
            int number = 0;
            while (number < 3)
            {
                System.Console.WriteLine(number);
                number++;
            }
        }

        static void Main()
        {
            int x = 0;

            Program increment = new Program(x);
            increment.checkNumber();
            Console.ReadLine();
        }
    }
}

The output from running the above code will be 0,1,2.

Series Navigation<< C#: If Else
C#: Read a file using while statement >>