Loops
While Loops
Decision Making
A loop statement allows to repeatedly execute a
statement or group of statements.
A while loop statement repeatedly executes a
target statement as long as a given condition is
true.
Example
The while loops check for the condition
x > 0. If it evaluates to true, it
executes the statements within its
body. Then it checks the statement
again and repeats.
Another loop structure is the for loop, which
allows writing of a loop that needs to execute a
specific number of times.
Example
Syntax:
for(initialization; condition; increment/decrement)
{
statement(s)
}
Initialization expression executes only once during the
beginning of the loop.
The condition is evaluated each time the loop iterates.
The loop executes the statement repeatedly until this
condition returns false.
Increment/Decrement executes after each iteration of
the loop.
The following example prints the
numbers 1 through 5.
This initializes x to the value 1, and
repeatedly prints the value of x, until
the condition x<=5 becomes false. On
each iteration, the statement x++ is
executed, incrementing x by one (1).
You can have any type of condition and any type
of increment statements in the for loop. The
example below prints only the even values
between 0 and 10.
Example
do-while Loops
The do-while Loops
A do-while loop is like a while loop, except that a
do-while loop is guaranteed to execute at least
one (1) time.
Example
Loop Control Statements
The break and continue statements change the
loop’s execution flow.
The break statement terminates the loop and
transfers execution to the statement
immediately following the loop.
Example
The continue statement causes the loop to skip
the remainder of its body and then
immediately retest its condition prior to
reiterating. In other words, it makes the loop
skip to its next iteration.
Example
END