if - Jaeki Song

Lecture 02
Control Structure
Jaeki Song
Outline
• Selection
– if statement
– switch statement
• Repetition
– while statement
– for statement
Control Structure
• A standard progression of logical steps to
control the sequence of statement execution
• Basic control structures
– Sequence
– Selection
– Repetition
Sequence Logical Control Structure
• This is the overriding
control structure.
• Instructions are carried
out in order or
sequence.
• Action can be inputs,
processes, or outputs
Action 1
Action 2
Action 3
Selection Logical Control Structure I
• Instructions are
executed
depending on the
outcome of a
test; also called
branching
– If….then….else
Condition is FALSE
Condition is TRUE
Condition
Action 1
Action 2
Selection Logical Control Structure II
• Case control structure
– Allow more than two choices when the condition
evaluated
Condition
Conditio1 is TRUE
Action 1
Conditio2 is TRUE
Action 1
Conditio3 is TRUE
Action 1
Condition4 is TRUE
Action 1
Repetition Logical Control Structure
• Instructions are repeatedly executed until
the outcome of a test is false; also called
repetition or looping.
Do… While Structure
Do… Until Structure
FALSE
Condition
Action
TRUE
TRUE
Action
Condition
FALSE
The Selection Structure
• Selection
• Relational
Expressions
• if and switch
Statements
Selection
• Selection allows the program to branch in different
directions depending on the outcome of a
condition.
• The program selects an action if the condition is
true, and may select an alternate action if the
condition is false.
• A condition is often called a Relational Expression.
• In Java, selection may be implemented by the if
statement or by the switch statement.
Relational Expressions
• A Relational Expression consists of one or
more conditions that compare one value to
another.
• Conceptually, a relational operation yields
either a ‘true’ or ‘false’ result.
• Format:
operand relational_operator operand
Relational Expressions
<
Relational Operators
(0 is false, non-zero is true)
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
Relational Expressions
A Numerical Accuracy Problem
• The reason for this is that many decimal point numbers,
such as .01, cannot be represented exactly in binary with a
finite number of bits.
• For real operands, the general expression
operand1 == operand2
should be replaced by the condition
fabs(operand1 - operand2) < EPSILON
where EPSILON is some acceptable small value.
Relational Expressions
Logical Operators
• Logical operators allow us to create more
complex relational expressions.
– AND Operator (&&) - if comparisons on both
sides are True, the whole condition is true.
– OR Operator (||) - If either or both comparisons
are True, the whole condition is True.
– NOT Operator (!) - A unary logical operator
that makes what was True False and what was
False True.
The if Statement
• Branch only if the condition is True
• Format
if (relational expression)
{ block of statements to be executed if
relational expression is true
}
The if Statement
The else Clause
• Branch in one direction if test is True,
another if False.
• Format:
if (relational expression)
{ block of statements executed when True
}
else
{ block of statements executed when False
}
Example
if (studentGrade >= 60)
System.out.println (“ Passed”);
else
System.out.println (“Failed”)
true
Grade >= 60
false
Print “passed”
The if Statement
Nesting if Statements
• if and if-else statements can contain any
valid JAVA statements, including other if or
if-else statements.
• Placing an if or if-else within an if or if-else
is called nesting.
• When nesting if-else statements within on
another, care must be taken. The pairing of
if’s and else’s can be tricky!
If..else and if…else if Statement
if (StudentGrade >= 90)
System.out.println (“A”);
else
if (StudentGrade >= 80)
System.out.println (“B”);
else
if (StudentGrade >= 70)
System.out.println (“C”);
else
if (StudentGrade >= 60)
System.out.println (“D”);
else
System.out.println(“F”);
if (StudentGrade >= 90)
System.out.println (“A”);
else if (StudentGrade >= 80)
System.out.println (“B”);
else if (StudentGrade >= 70)
System.out.println (“C”);
else if (StudentGrade >= 60)
System.out.println (“D”);
else
System.out.println(“F”);
Example: Grade
The switch Operator
• Used as a multi-branch alternative to the if
statement.
• Tests for equality.
• Can only be used with to compare integral
values.
Multiple Selection
• Case control structure
– Allow more than two choices when the condition
evaluated
Condition
Conditio1 is TRUE
Action 1
Conditio2 is TRUE
Action 1
Conditio3 is TRUE
Action 1
Condition4 is TRUE
Action 1
The switch Operator
• Multiple selection
operation
switch(expression)
{
case value1:
statement1;
statement2;
…
break:
case value2:
statementn;
statementm;
…
break:
default:
statementaa;
statementbb;
…
}
Example: Shipping Option
The Repetition Structure
• Repetition
• Pre-Test Repetition
– Sentinel Value Loop
• Post-Test Repetition
– Fixed-Count Loop
• Nested Loops
Repetition Logical Control Structure
• Allows for repeated execution of a set of
statements based upon the outcome of a
condition or test.
– Also known as looping or iteration.
• Two components of a repetition structure:
– Relational Expression or Test
– Loop Body
Repetition Logical Control Structure
Relational Expressions
• Relational expression
– Set up as for Selection.
– Always evaluates to either True (any non-zero
value) or False (a zero value).
• Body is executed as long as the test is True.
• Exit the loop when test is False.
Repetition Logical Control Structure
Loop Body
• The Loop Body
– Is usually a block of code;
– Contains instructions that reflect the task to be
repeatedly performed;
– Can contain any valid Java statements
– Usually includes code so that the test will
eventually prove False (or an infinite loop
condition will result).
Repetition Logical Control Structure
Two Variations of Repetition - Pretest
• Pretest Repetition
– Condition is tested before the body is ever
executed.
– If test is False the first time it is executed, the
body will never execute.
– Implemented with while and for statements.
Repetition Logical Control Structure
Two Variations of Repetition - Pretest
• while loop can be used to implement pretest
repetition
• Format:
while (relational expression)
{ statements executed while test
is True
}
Repetition Logical Control Structure
Controlling Loops - Sentinels
• Sentinel Value
– A special response value that is used to indicate
when the loop should be terminated.
– The sentinel value often is a value that would
not occur in the normal course of operations.
– The variable that will be tested must be given
an initial value before it is tested!
– Often implemented with a while loop.
Repetition Logical Control Structure
Controlling Loops - Fixed-Count
Increment and Decrement Operators
Increment Operators
Decrement Operators
(all add 1 to the variable)
(all subtract 1 from the variable)
int icount = 0;
icount = icount + 1
int dcounter = 0;
dcounter = dcounter - 1
icount += 1
dcounter -= 1
icount++
dcounter--
++icount
--dcounter
Example
• Class Average Program
• Shipping Charges
Repetition Logical Control Structure
Two Variations of Repetition - Pretest
• for loop can also be used to implement
pretest repetition
• Format:
for(initialization; expression; altering)
{ statements executed while condition
is True
}
Repetition Logical Control Structure
Controlling Loops - Fixed-Count
• Fixed-Count Loop
– Used when you want to execute the body a set number
of times.
– Uses a counter variable in the test condition to control
the loop.
– The counter variable must be initialized before
condition is tested.
– Usually implemented with a for loop.
Loop condition and final value
– E.g.;
for (int counter = 1; counter <=10 ; counter++)
Control variable name and initial value
Increment of control variables
Output Format
Pakage from java.text:
import java.text.DecimalFormat;
DecimalFormat precisionTwo = new Decimal Format (“0.00”)
Pakage from javax.swing
Number of columns
import javax.swing.JTextArea;
JTextArea outputTextArea = new JTextArea (11,20)
Number of rows
Example: for Repetition
Repetition Logical Control Structure
Two Variations of Repetition - Posttest
• Posttest Repetition
– Condition is tested after the body is
executed;
– Body is always executed at least once;
– Often used for data validation, where data
is validated as it is interactively entered.
– Implemented with do statement.
Repetition Logical Control Structure
Two Variations of Repetition - Posttest
• do-while loop is used to implement posttest
repetition
• Format:
do {
statements executed while
condition is True
} while (relational expression);
Repetition Logical Control Structure
The break Statement
• A break statement forces an immediate exit
from switch, while, for and do-while
statements.
– break violates the rules of good programming
practice, but can be useful for breaking out of
loops in certain, limited conditions.
– Format:
break;
Repetition Logical Control Structure
The continue Statement
• continue can be used only with while, dowhile, and for statements.
– When this statement is encountered, execution
is automatically transferred to the loop test.
– Format:
continue;