Do-While loop in Programming
Last Updated :
23 Jul, 2025
Do-while loop is a control flow statement found in many programming languages. It is similar to the while loop, but with one key difference: the condition is evaluated after the execution of the loop's body, ensuring that the loop's body is executed at least once. In this article, we will learn about the basics of Do while loop, its syntax and its usage in different languages.

What is Do-While Loop:
Do-while loop is a control flow statement (or loop statement) commonly found in many programming languages. It is similar to the while loop but with one crucial difference: the condition is evaluated after the execution of the loop's body. This ensures that the loop's body is executed at least once, even if the condition is initially false.
Do-While Loop Syntax:
The syntax of a do-while loop is as follows:
do {
// Statements to be executed
} while (condition);
- The block of statements within the
do
block is executed unconditionally for the first time. - After executing the block, the condition specified after the
while
keyword is evaluated. - If the condition evaluates to
true
, the loop body is executed again. If the condition evaluates to false
, the loop terminates, and program execution moves to the next statement after the loop.
Here's a breakdown of each component of the syntax:
do
: This keyword initiates the do-while loop and precedes the block of statements to be executed.{}
: These braces enclose the block of statements to be executed within the loop.while
: This keyword specifies the condition to be evaluated after the execution of the loop body.condition
: This is the expression that determines whether the loop should continue iterating. If the condition evaluates to true
, the loop continues; if it evaluates to false
, the loop terminates.
How does Do-While Loop work?
The do-while loop is a control flow construct used in programming to execute a block of code repeatedly until a specified condition becomes false. Here's how the do-while loop works:
- Initialization: The loop starts with the execution of the block of code inside the
do
statement. Unlike other loop types, the do-while loop guarantees that the block of code will be executed at least once, regardless of the condition. - Condition Evaluation: After executing the block of code inside the
do
statement, the condition specified in the while
statement is evaluated. This condition determines whether the loop should continue iterating or terminate. If the condition evaluates to true
, the loop continues to execute; if it evaluates to false
, the loop terminates. - Iterative Execution: If the condition evaluates to
true
, the loop body is executed again, and the process repeats. After each iteration, the condition is evaluated again to determine whether the loop should continue. - Termination: The loop terminates when the condition specified in the
while
statement evaluates to false
. Once the condition becomes false
, control exits the loop, and program execution proceeds to the next statement following the loop.
Do-While Loop in Different Programming Languages:
Do-While loops are fundamental constructs in programming and are supported by virtually all programming languages. While the syntax and specific details may vary slightly between languages, the general concept remains the same. Here's how Do-While loops are implemented in different programming languages:
1. Do-While loop in Python:
In Python, there is no native do-while
loop construct. However, you can achieve similar functionality using a while True
loop and a conditional break
statement to exit the loop when the desired condition is met.
Python
# Initialize a variable
count = 0
# Execute the loop body at least once
while True:
print(count) # Print the current value of count
count += 1 # Increment count by 1
if count >= 5:
break # Exit loop if count is equal to or greater than 5
Explanation: In Python, we initiate a while True
loop, ensuring that the loop body executes at least once. Inside the loop, we print the current value of count
and then increment it by 1
. The loop continues until the condition count >= 5
becomes True
, at which point we use a break
statement to exit the loop.
2. Do-While loop in JavaScript:
JavaScript's do-while
loop behaves similarly to other languages. It executes a block of code at least once and then evaluates the loop condition. If the condition is true, the loop continues; otherwise, it terminates.
JavaScript
let count = 0;
do {
console.log(count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
Explanation: In JavaScript, the do-while
loop prints the value of count
and increments it by 1
on each iteration. The loop body executes at least once, ensuring that the condition count < 5
is evaluated after the first execution. If count
is less than 5
, the loop continues executing.
3. Do-While loop in Java:
In Java, the do-while
loop is used to execute a block of code at least once before checking the loop condition. It guarantees that the loop body is executed at least once, even if the condition is initially false
.
Java
public class Main {
public static void main(String[] args) {
int count = 0;
do {
System.out.println(count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
}
}
Explanation: Here, we initialize a variable count
and use a do-while
loop to print its value and increment it by 1
on each iteration. The loop continues as long as count
is less than 5
. Even if count
is initially 5
or greater, the loop body executes at least once before the condition is checked.
4. Do-While loop in C:
In C, the do-while
loop is similar to other languages, executing a block of code at least once before evaluating the loop condition. The loop continues as long as the condition remains true.
C
#include <stdio.h>
int main() {
int count = 0;
do {
printf("%d\n", count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
return 0;
}
Explanation: In this C example, the do-while
loop prints the value of count
and increments it by 1
on each iteration. Similar to other languages, the loop body executes at least once, and the loop continues as long as the condition count < 5
remains true.
5. Do-While loop in C++:
Similar to Java, C++ also supports the do-while
loop, which guarantees that the loop body is executed at least once. The loop condition is evaluated after the first execution of the loop body.
C++
#include <iostream>
using namespace std;
int main() {
int count = 0;
do {
cout << count << endl; // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
return 0;
}
Explanation: Here, we initialize a variable count
and use a do-while
loop to print its value and increment it by 1
on each iteration. The loop continues as long as count
is less than 5
. Similar to Java, the loop body executes at least once before the condition is checked.
6. Do-While loop in PHP:
PHP's do-while
loop is similar to other languages, executing a block of code at least once before evaluating the loop condition. It continues looping as long as the condition remains true.
PHP
<?php
$count = 0;
do {
echo $count . "\n"; // Print the current value of count
$count++; // Increment count by 1
} while ($count < 5); // Continue looping as long as count is less than 5
?>
Explanation: In this PHP example, the do-while
loop prints the value of count
and increments it by 1
on each iteration. The loop body executes at least once, ensuring that the condition $count < 5
is evaluated after the first execution. If $count
is less than 5
, the loop continues executing.
7. Do-While loop in C#:
In C#, the do-while
loop is similar to Java and C++. It executes a block of code at least once before evaluating the loop condition. The loop continues as long as the condition remains true
.
C#
using System;
class MainClass {
public static void Main (string[] args) {
int count = 0;
do {
Console.WriteLine(count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
}
}
Explanation: In this C# example, the do-while
loop prints the value of count
and increments it by 1
on each iteration. The loop body executes at least once, even if the condition count < 5
is initially false. After the first execution, the condition is evaluated, and if count
is less than 5
, the loop continues executing.
These examples demonstrate how do-while loops are implemented and used in various programming languages. They guarantee the execution of the loop body at least once and then continue looping based on the specified condition.
Do-While Use Cases:
The do-while
loop, which guarantees the execution of its block of code at least once, is beneficial in various scenarios. Here are some common use cases:
1. Input Validation:
- When validating user input, especially in interactive programs, it's often necessary to prompt the user for input at least once, regardless of the initial validity of the input.
- The
do-while
loop ensures that the input validation logic is executed at least once before checking if the input meets the required criteria.
2. Menu-Driven Programs:
- In menu-driven applications where users make selections from a list of options, it's essential to display the menu to the user at least once.
- The
do-while
loop allows you to display the menu and prompt the user for input repeatedly until they choose to exit the menu.
3. File Processing:
- When reading or processing data from files, especially where the file may be empty or contain incomplete data, the
do-while
loop ensures that the file processing logic is executed at least once. - This allows you to handle edge cases gracefully and avoid errors due to unexpected file contents.
Do-While Loop vs Other Loops:
Here's a comparison table between the do-while loop and other common loop structures:
Aspect | Do-While Loop | While Loop | For Loop |
---|
Execution | Body executes at least once | Condition checked before execution | Initialization, condition check, iteration |
---|
Syntax | do { } while(condition); | while(condition) { } | for(initialization; condition; iteration) |
---|
Control Flow | Always executes at least once | May not execute if condition is false | May not execute if condition is false |
---|
Condition Evaluation | After the loop body | Before entering the loop body | Before entering the loop body |
---|
Loop Control Variables | May need to declare outside the loop | Typically declared outside the loop | Declared within the loop |
---|
Initialization | Not explicitly initialized in the loop | Not explicitly initialized in the loop | Initialized in the loop declaration |
---|
Use Cases | Input validation, game loops, error handling | Condition-based looping | Counter-based looping |
---|
Flexibility | Provides flexibility for executing code | Flexibility in defining condition | Flexibility in controlling loop parameters |
---|
In conclusion, the while loop emerges as a potent tool in the arsenal of any programmer, providing unmatched versatility and precision in controlling iteration. Mastering the intricacies of the while loop empowers developers to craft elegant, efficient, and robust solutions to a myriad of programming challenges.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem