How do I use while loop statement?

Category: Introduction, viewed: 2K time(s).

The while loop executes a statement or a block of statements until a specified expression evaluates to false. Because the test of the while expression takes place before each execution of the loop, a while loop execute zero or more times. It differs from the do loop, which executes one or more times.

using System;

namespace Kodecsharp.Example.Intro
{
    class WhileDemo
    {
        [STAThread]
        public static void Main(string[] args)
        {
            int number = 0;

            int result = 0;

            //
            // Iterate the while loop untile number is greater 
            // than 10.
            //
            while (number <= 10)
            {
                result = result + number;
                number++;

                Console.WriteLine("Temporary result: " + result);
            }

            Console.WriteLine("The total addition of " + 
                "number starting from 0 to 10 = " + result);
            Console.ReadLine();
        }
    }
}

The program prints the following result:

Temporary result: 0
Temporary result: 1
Temporary result: 3
Temporary result: 6
Temporary result: 10
Temporary result: 15
Temporary result: 21
Temporary result: 28
Temporary result: 36
Temporary result: 45
Temporary result: 55
The total addition of number starting from 0 to 20 = 55
Powered by Disqus