0
0
C Sharp (C#)programming~5 mins

Do-while loop execution model in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A do-while loop helps you repeat a set of actions at least once, then keep repeating as long as a condition is true.

When you want to ask a user for input and check it, repeating if the input is invalid.
When you need to run a process at least once before checking if it should continue.
When you want to show a menu and repeat it until the user chooses to exit.
When you want to perform an action and then decide if it should happen again based on the result.
Syntax
C Sharp (C#)
do
{
    // code to run
} while (condition);

The code inside do { } runs first, then the condition is checked.

If the condition is true, the loop repeats. If false, it stops.

Examples
This prints numbers 1 to 3, increasing count each time.
C Sharp (C#)
int count = 1;
do
{
    Console.WriteLine(count);
    count++;
} while (count <= 3);
This asks the user to type 'yes' and repeats until they do.
C Sharp (C#)
string input;
do
{
    Console.WriteLine("Enter 'yes' to continue:");
    input = Console.ReadLine();
} while (input != "yes");
Sample Program

This program prints numbers from 1 to 5 using a do-while loop.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int number = 1;
        do
        {
            Console.WriteLine($"Number is {number}");
            number++;
        } while (number <= 5);
    }
}
OutputSuccess
Important Notes

The do-while loop always runs the code inside at least once, even if the condition is false at the start.

Be careful to update variables inside the loop so the condition can become false and stop the loop.

Summary

The do-while loop runs code first, then checks the condition.

It repeats as long as the condition is true.

Use it when you want the code to run at least once before checking.