Control Flow Statements

This chapter provides tutorial notes and Control Flow Statements. Topics include decision-making statements: 'if' and 'switch' statements; looping statements: 'for', 'while' and 'do' statements; branching statements: 'break', 'continue', and 'return' statements.

What Is Control Flow Statement

"if-then" Statements

"if-then-else" Statements

Nested "if-then-else" Statements

"switch" Statements

Fall-Through Behavior of "switch" Statements

Basic "for" Statements

Enhanced "for" Statements

"while" Statements

"do" Statements

"break" Statements

Labeled "break" Statements

"continue" Statements

Labeled "continue" Statements

Conclusion:

• A Control Flow Statement is a statement that changes the default flow of execution, which run statements one by one sequentially.
• An "if-then" statement is a decision-making statement that executes the contained sub-statement only when the given "boolean" expression is "true".
• An "if-then-else" statement is a decision-making statement that executes only the first contained sub-statement when the given "boolean" expression is "true". Otherwise it executes only the second contained sub-statement.
• "if-then-else" statements can be nested as "if ... else if ... else if ... ... ... else".
• A "switch" statement is a decision-making statement that executes a portion of the contained statement block by passing control to a sub-statement based on label matching.
• A basic "for" statement is a looping statement that executes the contained statement repeatedly with an initial logic, a looping condition, and an update logic.
• An enhanced "for" statement is a looping statement that executes the contained statement repeatedly for each element in a given list.
• A "while" statement is a looping statement that executes the contained statement repeatedly while a given condition is true.
• A "do" statement is a looping statement that executes the contained statement immediately, then repeat it while a given condition is true.
• A non-labeled "break" statement is a branching statement that transfers the control to the end of the immediate enclosing "switch", "while", "do", or "for" statement.
• A labeled "break" statement is a branching statement that transfers the control to the end of the labeled enclosing block statement.
• A non-labeled "continue" statement is a branching statement that transfers the control to the end of the immediate enclosing loop block and continues the next iteration of the loop.
• A labeled "continue" statement is a branching statement that transfers the control to the end of the labeled enclosing loop block and continues the next iteration of the labeled loop.