-
Notifications
You must be signed in to change notification settings - Fork 0
Loops
Büşra Oğuzoğlu edited this page Jul 3, 2022
·
28 revisions
- In while loop, the
loop-continuation-conditionacts like an if statement. The loop will execute thestatementsrepeatedly when theloop-continuation-conditionis true. - In the loop body, we need to have an update statement that will eventually make the
loop-continuation-conditionfalse, so the loop will terminate.
while (loop-continuation-condition)
{
// Loop body
statements;
update-statement;
}- Unlike regular while loop, do-while loop it always executed at least once, since loop body is executed before the
loop-continuation-conditionis evaluated. - while statement behaves the same way as the regular while loop.
- while and do-while loops can be easily converted but using one or the other can be beneficial in some scenarios.
do {
// Loop body;
statements;
update-statement;
} while (loop-continuation-condition);for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
statements;
}It can be converted to a while loop:
initial-action;
while (loop-continuation-condition) {
// Loop body;
statements;
action-after-each-iteration;
}More precisely, these two loops are interchangable:
for (i = initialValue; i < endValue; i++) {
// Loop body
...
}i = initialValue; // Initialize loop control variable
while (i < endValue) {
// Loop body
...
i++; // Adjust loop control variable
}- We generally use this type of loop to iterate over the elements of a list of items. (Could be an ArrayList as an example)
- If we want to keep track of the index, or we want to skip some elements, it is better to use normal for loop.
for (type var : array)
{
// Loop body
statements using var;
}It is same as this for loop:
for (int i=0; i<arr.length; i++)
{
// Loop body
type var = arr[i];
statements using var;
}