Flow of Control

Sequence construct means the statements are being executed sequentially.

Selection construct means the execution of statements depend on a condition. Examples include if statement, if-else statements, if-else-if statements, conditional operators, switch statements.

Iteration construct means repetition of statements as long as the specified condition holds true.

Comparing if statement and conditional operator:
1. The conditional operator offers more compact code.
2. The if statement is more flexible.
3. The conditional operator becomes more complex when used in nested form.

The switch statement is a multiple-branch selection statement. The break keyword is used to exit from switch. The default keyword is used to provide statements to be executed when none of the cases match.

If the break statement is missing in each case, then the flow will continue executing the statements in the following cases as well. This is called fall through.

Comparing switch and if-else:
1. The switch statement can only test for equality, whereas the if statement can use other relational operators as well.
2. The switch statement doesn’t support ranges, whereas the if-else statement supports range of values.
3. The switch case only supports values of integer type, but if-else statement supports values of other data types as well.
4. The switch case label value must be a constant.
5. The switch statement is more efficient in situations that involve testing a value against a set of constants.
6. No two switch case labels can be identical.

Different parts of a loop include initialization expression, test expression, update expression, and body of the loop.

The for loop is the easiest among other loops. All its parts are gathered in one place. It is an entry-controlled loop.

An infinite loop is a loop that never terminates. It can be created in for loop by omitting the test expression. For other loops, the test expression should always evaluate to true.

An empty loop is one that does not contain any loop body.

The while loop is another entry-controlled loop. In this loop, the loop control variable is initialized before the loop begins, and the variable is updated inside the loop body.

The do-while loop is an exit-controlled loop. it evaluates the test expression at the bottom of the loop, after executing the loop body.

A nested loop is one in which a loop may contain another loop within its body.

The break keyword is used to exit from loops, by skipping the rest of the statements in the loop body.

The continue keyword skips the rest of the statements in the loop body and starts the next iteration of the loop.

Labels can be used with break and continue in cases where nested loops are present, and we want to specify which loop to target with break/continue.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.