While and Do-While Loops
Learn about the while and the do-while loop constructs in C++.
Several programming tasks consist of executing the same code multiple times. Tasks like moving an object across the screen, iterating through a list of items, searching through data, and performing mathematical operations on a stream of numbers; all consist of a block of code being executed repeatedly till a termination condition is met. C++ allows executing the same code several times using two different loop constructs:
The
while
loop and its variation thedo-while
loopThe
for
loop
The while
Loop
The while
loop is really the only necessary repetition construct. The for
loop and the do
- while
loop, coming up shortly, can be replicated using a while loop.
while ( condition ){//body}
Note: A while
statement doesn't use a semicolon at its end. It's because the semicolon is used to terminate statements, and the while
statement itself is a control structure that needs to be followed by a block of code to execute as long as the condition is true
.
A while
loop continues to run as long as the condition inside the parentheses is true
. If the condition is true
, the code inside the curly braces {}
is executed. After executing the last line inside the braces, the program checks the condition again. If it is still true
, the code inside the curly braces runs again. This cycle repeats ...