Do While loop
The Do While
loop is similar to While
loop.
The main difference is that Do While
checks the condition after it executes the body
.
It executes the body
at least once.
Let's write a program that reads a number from user.
If the entered number is not positive, we ask the user to enter a number again.
Steps:
- declare
x: Integer
- add a
Do While
block with conditionx <= 0
- input
x
in theDo While
body (arrow pointing from circle to theDo While
diamond)
We read it like this:
"Enter number x, as long as it is less than or equal to zero".
The Do While
loop will loop as long as the x <= 0
.
When the user enters a x > 0
the loop will exit, and the program will continue its execution.
Run the program and try various inputs: 1
, 17
, -55
, 6
, 0
.