Core C#

While Loops

A while loop can be used to loop while a condition holds. The condition is expressed by a boolean value that is either given or calculated. The while loop below runs until the speed is zero (or less). Inside the loop, the current speed is added to the distance as though each loop represented a slice of time. Then the speed is reduced as though it represents something like a vehicle slowing to a stop.

Program.cs

using System;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // A simple while loop
            int iSpeed = 10;
            int iDistance = 0;
            while (iSpeed > 0) {
                iDistance += iSpeed;
                Console.WriteLine("Distance Traveled: " + iDistance);
                --iSpeed;
            }
        }
    }
}
 

Output

Distance Traveled: 10
Distance Traveled: 19
Distance Traveled: 27
Distance Traveled: 34
Distance Traveled: 40
Distance Traveled: 45
Distance Traveled: 49
Distance Traveled: 52
Distance Traveled: 54
Distance Traveled: 55
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.