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:
Syntax
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
using System;
class Program
{
static void Main(string[] args)
{
int count = 0;
do
{
Console.WriteLine($"Running iteration {count}");
count++;
} while (count < 3);
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting the semicolon after
while (condition)at the end of a do-while. - Forgetting that the body always runs at least once.
- 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: