C# Do-While

Learning the 'do-while' Loop in C#.

The "while" loop executes its block of code as long as the given condition is true. In contrast, the "do-while" loop ensures that the block of code is executed at least once before checking the condition.

Do-While Loop

A 'do-while' loop is a control flow statement that repeats a block of code while a specified condition is true. The key difference between a 'do-while' loop and a 'while' loop is that the 'do-while' loop guarantees that the block of code is executed at least once, even if the condition is false from the beginning.

Basic syntax of a do-while loop in C#:

do {
    // Code to be executed
} while (condition);

The block of code is enclosed in curly braces '{}'. The 'do' keyword is followed by the code block, and then the 'while' keyword is used to specify the condition. The loop will continue to execute the code block as long as the condition is true.

Here's a simple example:

cs Copy Code
using System;

class Program
{
    static void Main()
    {
        int i = 0;

        do
        {
            Console.WriteLine(i);
            i++;
        } while (i < 5);
    }
}

The loop will print the values of 'i' from 0 to 4. The 'do-while' loop ensures that the block of code is executed at least once, regardless of the initial value of 'i' or the condition.

Output:
1
2
3
4
5

Remember: Keep in mind that the condition is checked after the execution of the block, so the block will always be executed at least once. If the condition is false after the first iteration, the loop will exit.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.