1unit 3
Flow of controlFlow of control
We will talk about:
• conditional statements if-then-else logical and conditional operators switch
• repetition statements while do for
basic programming
concepts
object oriented programming
topics in computer science
syllabus
2unit 3
Flow of ControlFlow of Control
Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written
Some programming statements modify that order, allowing us to:• decide whether or not to execute a particular
statement, or• perform a statement over and over repetitively
The order of statement execution is called the flow of control
3unit 3
Conditional StatementsConditional Statements
A conditional statement lets us choose which statement will be executed next; therefore they are sometimes called selection statements
Conditional statements give us the power to make basic decisions
Java's conditional statements are the if statement, the if-else statement, and the switch statement
4unit 3
The if StatementThe if Statement
The if statement has the following syntax:
if ( condition ) statement;
ifif is a Java is a Javareserved wordreserved word
The condition must be a The condition must be a boolean expressionboolean expression..It must evaluate to either true or falseIt must evaluate to either true or false..
If the condition is true, the statement is executedIf the condition is true, the statement is executed..If it is false, the statement is skippedIf it is false, the statement is skipped..
5unit 3
Logic of an if statementLogic of an if statement
conditionevaluated
falsefalse
statement
truetrue
SimpleIf
6unit 3
Example - class TemperatureExample - class Temperature
class Temperature { static final int THRESHOLD = 27;
public static void main(String[] args) {System.out.println(“Enter temperature:”);int temperature = EasyInput.readInt();
System.out.println(“Current temperature “+ temperature); if (temperature > THRESHOLD) System.out.println(“It’s hot in here!”);
}}
7unit 3
ConditionsConditions via Boolean Expressions via Boolean Expressions
The condition of an if statement must evaluate to a true or false result
Booleas values (true/false) are obtained by relational operators:
In relational operators the operands are numbers, the result is boolean
Operator
==!=<<=>>=
Meaning
equal tonot equal to
less thanless than or equal to
greater thangreater than or equal to
8unit 3
Block StatementsBlock Statements
Several statements can be grouped together into a block statement
Blocks are delimited by braces
A block statement can be used wherever a statement is called for in the Java syntax
9unit 3
Example – class Temperature2Example – class Temperature2
class Temperature2 { static final int THRESHOLD = 27;
public static void main(String[] args) { System.out.println(“Enter temperature:”); int temperature = EasyInput.readInt(); System.out.println(“Current temperature “+ temperature); if (temperature > THRESHOLD) { System.out.println(“It’s hot in here!”); System.out.println(“But we’ll survive.”); }
}}
10unit 3
Block StatementsBlock Statements
Q: assembly languages do not have blocks; what do they do instead?
11unit 3
If .. Else StatementIf .. Else Statement
An else clause can be added to an if statement to make it an if-else statement:if (condition)
statement1;
else
statement2;
If the condition is true, statement1 is executed; if the condition is false, statement2 is executed
12unit 3
Logic of an if-else statementLogic of an if-else statement
conditionevaluated
statement1
truetrue falsefalse
statement2
13unit 3
Example – class Temperature3Example – class Temperature3
class Temperature3 { static final int FREEZING_POINT = 0;
public static void main(String[] args) { System.out.println(“Enter temperature:”); int temperature = EasyInput.readInt(); if (temperature <= FREEZING_POINT) System.out.println(“It’s freezing!”); else System.out.println(“Above freezing.”); }}
14unit 3
Example – class RightTriangleExample – class RightTriangle
// Receives the length of the edges of a triangle// and determine if this is a right triangleclass RightTriangle { public static void main(String[] args) { double a = EasyInput.readDouble(“Edge1:”); double b = EasyInput.readDouble(“Edge2:”); double c = EasyInput.readDouble(“Hypotenuse:”); boolean test = a*a+b*b == c*c; if (test) System.out.println(“It’s a right triangle”); else System.out.println( “It’s not a right triangle.”); }}
15unit 3
Example: handling invalid inputExample: handling invalid input
int numberOfItems = EasyInput.readInt(“Enter number of items:”); if (numberOfItems < 0) { System.out.println( “Number of items must be positive!”);}else { double price = numberOfItems * ITEM_PRICE; System.out.println(“The total price is:“ +price);}
16unit 3
How to specify the conditionHow to specify the condition
simple if command:
if ( condition ) statement1;
else statement2;
The condition is determined via logical operators
logical operators operate on boolean variables, rather than numbers
17unit 3
Logical OperatorsLogical Operators
There are three logical operators in Java:
They all take boolean operands and produce boolean results
Logical NOT is unary (one operand), but logical AND and OR are binary (two operands)
Operator
!&&||
Operation
Logical NOTLogical ANDLogical OR
18unit 3
Logical NOTLogical NOT
The logical NOT is also called logical negation or logical complement
If a is true, !a is false; if a is false, then !a is true
Logical expressions can be shown using truth tables
a
falsetrue
!a
truefalse
19unit 3
Logical ANDLogical AND
The expression a && b is true if both a and b are true, and false otherwise
Truth tables show all possible combinations of all terms
a
falsefalsetruetrue
b
falsetruefalsetrue
a && b
falsefalsefalsetrue
20unit 3
Logical ORLogical OR
The expression a || b is true if a or b or both are true, and false otherwise
a
falsefalsetruetrue
b
falsetruefalsetrue
a || b
falsetruetruetrue
21unit 3
A note about truth tablesA note about truth tables
Any truth table defines a logical function
a
falsefalsetruetrue
b
falsetruefalsetrue
f(a,b)
falsefalsetruetrue
22unit 3
Logical Operators: what forLogical Operators: what for??
Logical operators are used to form more complex logical expressions
if (a<1 || a%2!=0) {
System.out.println(
“The input should be a positive “+
“even number!”);
return;
}
Logical operators have precedence relationships between themselves and other operators
23unit 3
Logical OperatorsLogical Operators
Full expressions can be evaluated using truth tables (like any logical function):
a < 1
falsefalsetruetrue
a%2!=0
falsetruefalsetrue
a<1 || a%2!=0
falsetruetruetrue
24unit 3
statement
truetrue
condition2evaluated
Nested if statementsNested if statements
IfAnd
falsefalse
condition1evaluated
truetrue
25unit 3
Example – class CompareExampleExample – class CompareExample// Receives 2 integers and compare themclass CompareExample { public static void main(String[] args) {
System.out.println (“First number:”); int a = EasyInput.readInt(); System.out.println (“Second number:”); int b = EasyInput.readInt(); if (a != b) if (a > b) System.out.println(a+” is greater”); else System.out.println(b+” is greater”); else System.out.println(“the numbers are equal”); }}
26unit 3
A note about styleA note about style
The statements within an if or if-else statement should always be put in a block statement; the previous example was written in a poor style
Use of block statements eliminates the confusion that can arise in the previous example (think of a longer code and many if-else statements)
Use of blocks can also avoid a type of semantic mistakes
27unit 3
The switch StatementThe switch Statement
The switch statement provides another means to decide which statement to execute next
The switch statement evaluates an expression, then attempts to match the result to one of several possible cases
Each case contains a value and a list of statements
The flow of control transfers to statement list associated with the first value that matches
28unit 3
The switch StatementThe switch Statement
The general syntax of a switch statement is:
switch ( expression ){
case value1 : statement-list1
case value2 : statement-list2
case value3: statement-list3
default:...
}
switchswitchandandcasecasearearereservedreservedwordswords
If If expressionexpressionmatches matches value2value2,,
control jumpscontrol jumpsto hereto here
29unit 3
The switch StatementThe switch Statement
Often a break statement is used as the last statement in each case's statement list
A break statement causes control to transfer to the end of the switch statement
If a break statement is not used, the flow of control will continue into the next case
Sometimes this can be helpful, but usually we only want to execute the statements associated with one case
30unit 3
The switch StatementThe switch Statement
A switch statement can have an optional default case
The default case has no associated value and simply uses the reserved word default
If the default case is present, control will transfer to it if no other case value matches
Though the default case can be positioned anywhere in the switch, it is usually placed at the end
If there is no default case, and no other value matches, control falls through to the statement after the switch
31unit 3
The switch StatementThe switch Statement
The expression of a switch statement must result in an integral data type, like an integer or character; it cannot be a floating point value
Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with a value
You cannot perform relational checks with a switch statement
32unit 3
The The switchswitch Statement Statement
// A client that enables you to connect to the
// bank server and make remote banking operations...
public class BankClient {
public static final int VIEW_BALANCE = 1;
public static final int VIEW_SAVINGS = 2;
public static final int CASH_TRANSFER = 3;
public static final int VIEW_LAST_OPERATIONS = 4;
// ...
33unit 3
The The switchswitch Statement Statement
// Inside the main loop of the client:int option = EasyInput.readInt(“Enter your choice:”);
switch(option) {case VIEW_BALANCE: showBalance(); break;case VIEW_SAVINGS: showSavings(); break;default: System.out.println(“No such option!”);}
34unit 3
simple if command:
if ( condition ) statement1;
else statement2;
The conditional operator is similar; but it is intended to select between different values, rather than between different actions
35unit 3
The Conditional OperatorThe Conditional Operator
Java has a conditional operator that evaluates a boolean condition, determining which of two expressions is evaluated:
condition ? expression1 : expression2
If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated
expression1 and expression2 must return a value! The result of the chosen expression is the result of
the entire conditional operator
36unit 3
The Conditional OperatorThe Conditional Operator
It is similar to an if-else statement, except that it is an expression that returns a value; for example:
int max = (a > b) ? a : b;
If a is greater than b, then a is assigned to max; otherwise, b is assigned to max
The conditional operator is ternary, meaning it requires three operands
37unit 3
The Conditional Operator: exampleThe Conditional Operator: example
System.out.println ("Your change is "
+ count +
((count == 1) ? "Dime" : "Dimes”));
• input count is 1, program will print: Your change is 1 Dime
• input count is 10, program will print: Your change is 10 Dimes
38unit 3
Flow of controlFlow of control
We will talk about:
• conditional statements if-then-else logical and conditional operators switch
• repetition statements while do for
basic programming
concepts
object oriented programming
topics in computer science
syllabus
39unit 3
Repetition StatementsRepetition Statements
Repetition statements allow us to execute a statement multiple times repetitively; they are often simply referred to as loops
Like conditional statements, they are controlled by boolean expressions
Java has three kinds of repetition statements: the while loop, the do loop, and the for loop; the programmer must choose the right kind of loop for the situation
40unit 3
The while StatementThe while Statement
The while statement has the following syntax:
while ( condition ) statement;
whilewhile is a is areserved wordreserved word
If the condition is true, the statement is executedIf the condition is true, the statement is executed..Then the condition is evaluated againThen the condition is evaluated again..
The statement is executed repetitively untilThe statement is executed repetitively untilthe condition becomes falsethe condition becomes false..
41unit 3
Logic of a while loopLogic of a while loop
statement
truetrue
conditionevaluated
falsefalse
FlowNestedIf
42unit 3
The while statementThe while statement
If the condition of a while statement is false initially, the statement is never executed; therefore, we say that a while statement executes zero or more times
As in the case of if, always use a block statement for the body of the while statement, even if it consists of only a single statement
43unit 3
Example – class CounterExample – class Counter
// Counts from 1 to 5class Counter { static final int LIMIT = 5;
public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“done”); }}
44unit 3
Examples – class FactorsExamples – class Factors
// Gets an integer and prints its factors
public static void main(String[] args) {
int a = EasyInput.readInt(“Enter a number:”);
int i = 1;
System.out.println(“The divisors of “+a+” are:”);
while(i <= a) {
if (a%i == 0) {
System.out.println(i);
}
i = i + 1;
}
}
45unit 3
Example – class PowersOfTwoExample – class PowersOfTwo
// Prints the first ten powers of twoclass PowersOfTwo { static final int LIMIT = 10; public static void main(String[] args) { int power = 1; int i = 1; while (i <= LIMIT) { power = power * 2; System.out.println(power); i = i + 1; } }}
46unit 3
Infinite LoopsInfinite Loops
The body of a while loop must eventually make the condition false; if not, it is an infinite loop, which will execute until the user interrupts the program
This is a common type of logical error -- always double check that your loops will terminate normally
47unit 3
Example – class ForeverExample – class Forever
// This program contains an infinite loop
class Forever {
static final int LIMIT = 25;
public static void main(String[] args) {
int count = 1;
while (count <=<= LIMIT) {
System.out.println(count);
count = count - 1;
}
}
}
48unit 3
The do StatementThe do Statement
The do statement has the following syntax:do{
statement;}while ( condition )
Uses bothUses boththe the dodo and andwhilewhilereservedreservedwordswords
The statement is executed once initially, then the condition is evaluatedThe statement is executed once initially, then the condition is evaluated
The statement is repetitively executed until the condition becomes falseThe statement is repetitively executed until the condition becomes false
49unit 3
Logic of a do loopLogic of a do loop
truetrue
conditionevaluated
statement
falsefalse
50unit 3
The do StatementThe do Statement
A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed
Therefore the body of a do loop will execute at least one time
51unit 3
Comparing the while and do loopsComparing the while and do loops
statement
truetrue
conditionevaluated
falsefalse
while loopwhile loop
truetrue
conditionevaluated
statement
falsefalse
do loopdo loop
52unit 3
The for StatementThe for Statement
The for statement has the following syntax:
for ( initialization ; condition ; increment ) statement;
ReservedReservedwordword
The The initializationinitialization portion portionis executed onceis executed oncebefore the loop beginsbefore the loop begins
The statement isThe statement isexecuted until theexecuted until theconditioncondition becomes false becomes false
The The incrementincrement portion is executed at the end of each iteration portion is executed at the end of each iteration
53unit 3
The for StatementThe for Statement
is equivalent to the following while loop:
initialization;while ( condition ){
statement; increment;
}
for ( initialization ; condition ; increment ) statement;
54unit 3
Logic of a for loopLogic of a for loop
statement
truetrue
conditionevaluated
falsefalse
increment
initialization
55unit 3
initialization
Comparing the while and for loopsComparing the while and for loops
statement
truetrue
conditionevaluated
falsefalse
while loopwhile loop
statement
truetrue
conditionevaluated
falsefalse
for loopfor loop
increment
56unit 3
The for StatementThe for Statement
Like a while loop, the condition of a for statement is tested prior to executing the loop body
Therefore, the body of a for loop will execute zero or more times
It is well suited for executing a specific number of times that can be determined in advance
57unit 3
The The forfor Statement: examples Statement: examples
for (int count=1; count < 75; count++) {
System.out.println (count);
}
for (int num=5; num <= 10; num *= 2) {
sum += num;
System.out.println (sum);
}
58unit 3
The The forfor Statement Statement
Each expression in the header of a for loop is optional• If the initialization is left out, no initialization is
performed• If the condition is left out, it is always considered
to be true, and therefore makes an infinite loop• If the increment is left out, no increment operation
is performed
Regardless, both semi-colons are always requiredFlowIfElse
59unit 3
The The breakbreak and and continuecontinue statements statements
The break statement, which we used with switch statements, can also be used inside a loop: when the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again)
A similar construct, the continue statement, can also be executed in a loop: when the continue statement is executed, control jumps to the end of the loop and the condition is evaluated
60unit 3
Nested Loops - Multiplication TableNested Loops - Multiplication Table
int numRows = EasyInput.readInt(“Enter number of rows”);int numColumns = EasyInput.readInt(“Enter number of columns”);
for (int row = 1; row <= numRows; row++) {
for (int column = 1; column <= numColumns; column++) { System.out.print(row * column + “ “); }
System.out.println();}
61unit 3
Nested LoopsNested Loops
public class Mystery {
public static void main(String[] args) {int dimension =
EasyInput.readInt(“Enter dimension”);
for (int j = 0; j < dimension; j++) { for (int k = 1; k < dimension - j; k++) { System.out.print(" "); } for (int k = 0; k < j; k++) { System.out.print("*"); } System.out.println(); } } }
62unit 3
Why do We Need IndentationWhy do We Need Indentation??
public class Mystery {
public static void main(String[] args) {InputRequestor in = new InputRequestor();int dimension = EasyInput.readInt(“Enter dimension”);
for (int j = 0; j < dimension; j++) {for (int k = 1; k < dimension - j; k++) {System.out.print(" ");} for (int k = 0; k < j; k++) {System.out.print("*");} System.out.println();}} }
63unit 3
What you should be able to do nowWhat you should be able to do now......
write a program which can: decide online which piece of code to follow repeat a piece of code a number of times
exercise: compute the divisors of a number (class Factor) in 3 different ways
Top Related