C# do while Loop
It is used when it is not possible to predict how many times the loop will return, as in the while loop.
The most important difference from the while loop is that the condition is checked at the end of the loop. Therefore, when we use the do while loop, it means that the operations in the loop will be performed at least once.
Its structure is as follows:
do
{
Transactions...
}
while( running condition of the loop );
Do not forget to put a semicolon after the last while line.
Do While Loop Example
The program that continues to ask for numbers until the user enters 0, adds the entered numbers to the total, ends the loop when he enters 0 and writes the total to the screen:
int total=0, number;
do
{
Console.Write("Number: ");
number = int.Parse(Console.ReadLine());
total += number;
} while (number != 0);
Console.WriteLine(total);
Console.ReadKey();
C# Console - Number Guessing Game with do while Loop
In this example, the computer will generate a random number at first, then the user will be asked for the number continuously in the loop . The number entered by the user will continue as long as it cannot be known by comparing it with what the computer is holding. You will also be given a hint of "Down" or "Up".
On the one hand, the user will have the right to try 10 times, and this right will be reduced one at a time, and when it is 0, the cycle will end.
int counter = 1;
int guess;
Random random = new Random();
int heldNumber = random.Next(0, 1000);
do
{
Console.Write(counter + ". Enter your guess: ");
guess = int.Parse(Console.ReadLine());
if (guess > heldNumber && counter<=10) Console.WriteLine("Down");
else if (guess < keptNumber && counter <= 10) Console.WriteLine("Up");
else if (guess == heldNumber)
{
Console.WriteLine("CONGRATULATIONS..." + counter + ". you tried it. ");
}
counter++;
if (counter > 10)
Console.WriteLine("You have expired!");
}
while (guess != heldNumber && counter<=10);
Console.ReadKey();
c# console do while loop tutorials, difference between do while and while loop, do while examples
EXERCISES
There are no examples related to this subject.
Read 714 times.