Core C#

Do While Loops

A do while loop can be used to loop while a condition holds. However, unlike a while loop, a do while loop does not require that the condition hold before entering the loop. The condition is expressed by a boolean value that is either given or calculated. The do while loop below runs until the temperature is less than zero. Inside the loop, sign of the temperature is flipped. The loop runs twice because it takes two flips to become negative again. Note that if this were a while loop, the code would never enter the loop because the temperature is initially negative.

Program.cs

using System;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // A simple do while loop
            int iTemp = -10;
            do {
                Console.WriteLine("Temperature: " + iTemp);
                iTemp *= -1;
            } while (iTemp > 0);
        }
    }
}
 

Output

Temperature: -10
Temperature: 10
Press any key to continue . . .
 
 

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