While-Loop-4
While-Loop-4
Definition
• entry-controlled
• a condition is assessed before processing the loop’s body
• a loop’s body will be executed if and only if a condition is met
Use
• used to repeatedly run a block of code up until a predetermined condition is
satisfied
Importance
• in order to create a short code block to do specific code statement/s repeatedly
until a certain condition is met for the program to stop the loop
Illustration
How while() loops function:
• The while loop evaluates the condition.
• If condition is true, statements inside the body of the while loop are executed.
Then, condition is re-evaluated.
• The process goes on until condition is evaluated to be false.
• If condition is false, the loop terminates.
How while() loops function: (cont’d)
Suppose we are going to use the while loop to output numbers 1 to num, the process would go
on like this:
Syntax
• Test Expression: We must test the condition in this expression. If the condition is true,
we will run the loop’s body and proceed to the update expression; otherwise, we will
leave the loop.
• Update Expression: After executing the loop body this expression
increments/decrements the loop variable by some value.
Example
Do you have
any
questions?