Microlink IT and Business College
Postgraduate Studies
Department of MIS
1
Chapter 3-Loops and Flow Control
Structures
Compiled By: Solomon H. (Asst.
Prof.)
Loops and Other Flow-Control Structures
2
Very rarely will a program execute
sequentially, line by line.
Execution path through a program’s logic will often
be conditional.
It may be necessary to have the program to:
execute a certain block of code if some condition is
met, or a different block of code if the condition isn’t
met, or
repeatedly execute a particular block of code a fixed
number of times, or until a particular result is
attained.
if Statements
3
executes one or more lines of code if a
condition is satisfied and other lines of code if
the condition is not satisfied by placing that
code after the keyword else.
The use of an else clause is optional.
Syntax:
if (logical-expression) {
execute whatever code is contained within these
braces
if logical-expression evaluates to true
}
if Statements…
4
Or:
if (logical-expression) {
execute whatever code is contained within these braces
if logical-expression evaluates to true
}
else {
execute whatever code is contained within these braces
if
logical-expression evaluates to false
}
if Statements…
5
If only one executable statement follows
either the if or (optional) else keyword, the
braces can be omitted:
if (logical-expression) single statement to execute if
logical-expression is true;
else single statement to execute if logical-expression is
false;
Example:
if (x > 3) y = x;
else z = x;
But it’s good practice to always use braces.
if Statements…
6
A single boolean variable, as a simple form of
Boolean expression, can serve as the logical
expression/condition of an if statement.
Example:
if Statements…
7
It’s possible to nest if-else constructs to test more than one
condition.
If nested, an inner if (plus optional else) statement is placed
within the else part of an outer if.
Example:
if (logical-expression-1) {
execute this code
}
else {
if (logical-expression-2) {
execute this alternate code
}
else {
execute this code if neither of the above expressions evaluate to true
}
}
if Statements…
8
There’s no limit to how many nested if-else constructs
can be used, although if nested too deeply, the code may
become difficult for a human reader to understand and
hence maintain.
The above example may be alternatively written without
nesting as follows:
if (logical-expression-1) {
execute this code
}
else if (logical-expression-2) {
execute this alternate code
}
else {
execute this code if neither of the above expressions evaluate to true
}
switch Statements
9
is similar to an if-else construct-allows the
conditional execution of one or more lines of
code.
compares the value of an int or char expression
against values defined by one or more case
labels.
If a match is found, the code following the
matching case label is executed.
An optional default label can be included to
define code that is to be executed if the
expression matches none of the case labels.
switch Statements…
10
Syntax:
switch (int-or-char-expression) {
case value1:
one or more lines of code to execute if value of
expression matches value1
break;
case value2:
one or more lines of code to execute if value of
expression matches value2
break;
// more case labels, as needed ...
switch Statements…
11
Example:
switch Statements…
12
NB:
The expression in parentheses following the switch
keyword must be an expression that evaluates to a char
or int value.
The values following the case labels must be constant
values (a “hardwired” integer constant or character
literal).
Colons (:), not semicolons (;), terminate the case and
default labels.
The statements following a given case label don’t have to
be enclosed in braces-they constitute a statement list
rather than a code block.
switch Statements…
13
A switch statement isn’t automatically terminated when
a match is found and the code following the matching
case label is executed.
To exit a switch statement, a break statement must be
used.
If a break statement isn’t included following a given case
label, execution will “fall through” to the next case or
default label.
advantage:
when the same logic is to be executed for more than one case label,
two or more case labels can be stacked up back to back, as shown
here:
switch Statements…
14
// x is assumed to have been previously declared as an int
switch (x) {
case 1:
code to be executed if x equals 1
case 2:
code to be executed if x equals 1 OR 2
case 3:
code to be executed if x equals 1, 2, OR 3
break;
case 4:
code to be executed if x equals 4
}
for Statements
15
is used to execute one or more statements a
certain number of times.
syntax:
for (initializer; condition; iterator) {
code to execute while condition evaluates to true
}
Initializer
provides an initial value for a loop control
variable.
can be declared as part of the initializer, or it
can be declared ahead of the for statement.
for Statements…
16
Example:
for (int i = 0; condition; iterator) {
code to execute while condition evaluates to true
}
versus
int i;
for ( i = 0; condition; iterator) {
code to execute while condition evaluates to true
}
for Statements…
17
Condition
is a logical expression that involves the loop
control variable:
for (int i = 0; i < 5; iterator) {
code to execute as long as the value of i remains less than 5
}
Iterator
increments or decrements the loop control
variable:
for (int i = 0; i < 5; i++) {
code to execute as long as the value of i remains less than 5
}
for Statements…
18
How a for loop operates?
1. When program execution reaches a for statement, the
initializer is executed first (and only once).
2. The condition is then evaluated. If the condition
evaluates to true, the block of code following the
parentheses is executed.
3. After the block of code finishes, the iterator is
executed.
4. The condition is then reevaluated. If the condition is
still true, the block of code is executed once again,
followed by execution of the iterator statement.
This process repeats until the condition becomes false, at
which point the for loop terminates.
for Statements…
19
Example:
while Statements
20
If it’s impractical to predict the number of times
that the code block is to be executed when the
loop first begins, a while statement is the
preferred choice, because it continues to
execute as long as a specified condition is met.
Syntax:
while (condition) {
code to repeatedly execute while condition continues to
evaluate to true
}
while Statements…
21
The condition can be either a simple or a
complex logical expression that evaluates to a
true or false value.
Example:
int x = 1,y=1;
while ((x < 20) || (y < 10)) {
hopefully we'll do something within this loop body that
increments the value of either x or y, to avoid an infinite
loop!
}
while Statements…
22
When program execution reaches a while
statement, the condition is evaluated first.
If the condition is true, the block of code
following the condition is executed.
When the block of code is finished, the condition
is evaluated again, and if it’s still true, the
process repeats itself until the condition
evaluates to false, at which point the while loop
terminates.
while Statements…
23
Example:
Jump Statements
24
are used to redirect program execution to
another statement elsewhere in the code.
Are of two types: break and continue
statements.
Break statement
can also be used to abruptly terminate a for or
while loop.
When encountered, the loop immediately
terminates, and program execution is
transferred to the line of code immediately
following the loop:
Jump Statements…
25
Jump Statements…
26
Continue statement
is used to exit from the
current iteration of a
loop without terminating
overall loop execution.
transfers program
execution back up to the
top of the loop without
finishing the particular
iteration that is already in
progress; the loop counter
is incremented, in the
case of a for loop, and
execution continues.
Block-Structured Languages and the Scope of
a Variable
27
Java is a block-structured language.
a “block” of code is a series of zero or more lines
of code enclosed within braces { ... }.
Blocks may be nested inside one another to any
arbitrary depth:
Example:
int x=3,y=4,z=5;
if (x > 2) {
if (y > 3) {
}
}
Block-Structured Languages and the Scope of a
Variable
28
Variables can be declared in any block within a program.
The scope of a variable is that portion of code in which
the variable can be referenced by name—specifically,
from the point where the variable name is first declared
down to the closing (right) brace for the block of code in
which it was declared.
A variable is said to be in scope as long as the compiler
recognizes its name.
Once program execution exits a block of code, any
variables that were declared inside that block go out of
scope and will be inaccessible to the program; the
compiler effectively forgets that the variable was ever
declared.
Block-Structured Languages and the
Scope of a Variable
29
Printing to the Screen
30
Most applications communicate information to
users by displaying messages via an
application’s GUI.
It’s also useful to be able to display simple text
messages to the command line window from
which we’re running a program as a quick and
dirty way of verifying that a program is working
properly.
Syntax:
System.out.println(expression to be printed);
Printing to the Screen…
31
Examples:
print vs. println
32
print vs. println…
33
Escape Sequences
34
Java defines a number of escape sequences so
that we can represent special characters, such
as newline and tab characters, within String or
char literals.
Escape Sequences…
35
Elements of Java Style
36
One of the trademarks of good programmers is
that they produce human-readable code, so
that their colleagues will be able to work with
and modify their programs.
guidelines and conventions to produce clear,
readable Java code are:
Proper Use of Indentation
37
One of the best ways to make
a Java program readable is
through proper use of
indentation to clearly
delineate its block structure.
Statements within a block of
code should be indented
relative to the starting/ending
line of the enclosing block
(i.e., indented relative to the
lines carrying the braces).
Use Comments Wisely
38
Always keep in mind when writing code that
you may know what you’re trying to do, but
someone else trying to read your code may
not.
We sometimes need to remind ourselves of why we
did what we did if we haven’t looked at code that
we’ve written in a while!
Use Comments Wisely…
39
Some basic rules of thumb:
If there can be any doubt as to what a passage of code
does, precede it with a comment.
Indent each comment to the same level as the block of
code or statement to which it applies.
Make sure that all comments add value—don’t state
the obvious!
Placement of Braces
40
For block-structured languages
that use braces to delimit the
start/end of blocks, there are
two general schools of thought
as to where the left/opening
brace of a code block should be
placed.
style 1:
place an opening brace at the
end of the line of code that
starts a given block. Each
closing brace goes on its own
line, aligned with the first
character of the line containing
the opening brace:
More compact
More popular
Placement of Braces…
41
Style 2:
place every opening
brace on a line by itself,
aligned with the
immediately preceding
line.
Each closing brace goes
on its own line as before,
aligned with the
corresponding opening
brace:
Placement of Braces…
42
N.B.
It’s a good practice to maintain consistency in
your code, however, so pick whichever brace
placement style you prefer and stick with it.
Descriptive Variable Names
43
the goal when choosing variable names is to
make a program as readable, and hence self-
documenting, as possible.
Avoid using single letters as variable names,
except for loop control variables.
Abbreviations should be used sparingly, and
only when the abbreviation is commonly used
and widely understood by developers.
Consider the following variable declarations:
int grd; //vs
int grade;
Descriptive Variable Names…
44
names that are too long—such as perhaps
double averageThirdQuarterReturnOnInvestment;
can make a code listing overwhelming to anyone
trying to read it.
do try to keep the length of your variable names
within reason, for example:
double avg3rdQtrROI;
Comments/Suggestions
45