cpp / beginner
Snippet
Do-While Loop Basics
The do-while loop is a post-condition loop that always executes its body at least once before checking the condition. The syntax is: do { statement; } while (condition);. This is useful when you need to perform an action first and only decide whether to repeat based on the result. Contrast this with the while loop which checks the condition before executing the body.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>int main() {int count = 1;do {std::cout << "Count: " << count << std::endl;count++;} while (count <= 5);return 0;}
Breakdown
1
do { ... }
Starts the loop body that will execute at least once
2
std::cout << "Count: " << count << std::endl;
Prints current count value each iteration
3
count++;
Increments count by 1 after printing
4
} while (count <= 5);
Condition checked AFTER body executes; loop repeats if true
5
while (count <= 5)
Unlike while, this would check BEFORE first execution