← Back to C# Course | Chapter 4: Control Flow | Lesson 5 of 7

do-while Loop

A do-while loop does the action first and asks afterward whether to repeat, like taking a bite of food and then deciding if you want more. It always runs at least once.

In this page:

  1. do-while Loop
Syntax
csharp
do
{
    // body runs at least once
} while (condition);

do-while Loop

A do-while loop checks its condition *after* running the body, guaranteeing the body executes at least once. This differs from while, which may skip the body entirely.

It's commonly used for menu-style loops that must run once before checking whether to repeat.

Note: Use do-while when the loop body must run at least one time, like reading initial user input.

Example: do-while Loop

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int count = 0;

        do
        {
            Console.WriteLine($"Running iteration {count}");
            count++;
        } while (count < 3);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the semicolon after while (condition) at the end of a do-while.
  2. Forgetting that the body always runs at least once.
  3. Never changing the condition variable, creating an infinite loop.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.