Loops Flashcards
Programming constructs
- They can be defined as types of statements in a programming language.
- Sequence, Selection and Iteration are the three types of programming constructs that are provided in every programming language to support sequence, selection and iteration.
- In a program, statements may be executed sequentially, selectively or iteratively
For loop
A “for loop” is a repetition control structure
that allows you to repeatedly execute one or
more statements a specific number of times.
Entry controlled loop
A loop in which the body of the loop is executed only if the test expression is true.
Infinite loop
An infinite loop is basically a loop that runs
indefinitely. It normally occurs if the test
condition is always true. It results in a logical
error.
Empty loop
If a loop does not contain any statement in its
loop-body, it is said to be an Empty loop.
Purpose of empty loops
Empty loops can be used as Timer loops and also
for making the code more compact.
While loop
The while loop continually executes a block
of statements while a particular condition
is true.
In a while loop, a loop control variable should
be initialized before the loop begins, as an
uninitialized variable cannot be used in the
expression in the while statement.
The loop variable should be updated inside
the body of the while loop.
Comparison of for and while
Similarity:
Both are Entry-controlled loops.
Difference:
In a ‘for’ loop construct, initialization,
conditional expression and update statement
can be in the loop statement, whereas in a
‘while’ loop construct, only the conditional
expression can be in the loop statement
Do…while
A loop that is similar to the while loop except that the do while loop is guaranteed to execute at least once
Exit controlled loop
A loop in which the conditions are tested after at least one iteration of the loop body
Difference between while and do while loop
While Do while
Entry controlled Exit conrolled
Boolean expression before Boolean expression after
loop body loop body
Statements are executed only Statements are executed
if the expression is true. at least once and they
are executed again if they
are true.