How do I use while loop statement?

Category: Introduction, viewed: 157 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
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page