Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
MT-201 Unit 6 : Advanced control structures & squares
A) Complex logical expressions
And [&&], Or [ || ] , Not [ ! ]
Short-circuit evaluation of logical expressions
Bitwise operators [&], [ | ], [ ^ ]
B) Advanced branching statements
Nested [ if / else ] statement
[ break ] in [ switch / case ] statements
C) Advanced looping statements
D) Sorting (Insertion sort)
E) Multidimensional squares
F) Recursion — an advanced control structure
http://learn.ouhk.edu.hk/~t441063
1
A) Complex logical expressions
How to express the following formula in Java ?
0 x 100
How about ?
If ( 0 < x < 100 ) {
......
}
Wrong !? How about adding more brackets ?
If ( (0 < x ) < 100 ) {
......
}
Still wrong. Depending on the content in x , it is :
If ( true < 100 ) {
......
}
If ( false < 100 ) {
......
}
Correct syntax :
If ( (0 < x) && ( x < 100 )) {
......
}
If ( (x > 0) && ( x < 100 )) {
......
}
2
The [ && ] operator
in Table 6.1, conditions a and b denotes two
conditions with values of either true or false
Each row in the table is a possible combination of
values of conditions a and b.
rightmost column is result of conditions a && b.
Condition
Result
a
true
true
b
true
false
a && b
true
false
false
false
true
false
false
false
Table 6.1 Truth table of the [ && ] operator
3
Case-1 :
(0 < x) && ( x < 100 )
We can treat sub-condition (0 < x ) as a and (x < 100 ) as b
The given expression can be visualized in Figure 6.1, where
All possible result values of the given expression for variable x are
partitioned in three regions
Only the blue region can give a value true
The other 2 red regions will give a value false
(0 < x)
-50
-1
0
1
(0 < x) is false
So,
(0 < x) && ( x < 100 )
will return false
(x < 100)
50
99 100 101
(0 < x ) is true and
(x < 100 ) is true
So,
(0 < x) && ( x < 100 )
will return true
150
( x < 100 ) is false
So,
(0 < x) && ( x < 100 )
will return false
Figure 6.1 A number line with the two values 0 and 100 indicated
4
from Table 6.1, we can make Table 6.2 with different values of x
Table 6.2 helps you investigate the relationship between the results of
sub-conditions and the overall result
It helps you verify whether a condition is properly constructed
Value of
x
Result of
x>0
Result of
x < 100
Result of
( (0<x) && (x<100) )
-50
(-50 >0)
false
(-50 <100) true
false
0
(0 >0)
false
( 0 <100) true
false
50
(50 >0)
true
( 50 <100) true
true
100
(100 >0)
true ( 100 <100) false
false
150
(150 >0)
true ( 150 <100) false
false
Table 6.2 Truth table for condition (x > 0) && (x < 100) for various values of x
(0 < x)
-50
-1
0
1
(x < 100)
50
99 100 101
150
5
Case-2 : (x < 0) && ( x > 100 )
Now, the condition is modified.
Table 6.3 with different values of variable x is made as follows
Value of
x
Result of
x<0
Result of
x > 100
Result of
( (x<0) && (x>100) )
-50
(-50 <0)
true
(-50>100) false
false
0
(0 <0)
false
(0 >100) false
false
50
(50 <0)
false
(50 >100) false
false
100
(100 <0) false
(100>100) false
false
150
(150 <0) false
(150>100) true
false
Table 6.3 Truth table for condition (x < 0) && (x > 100) for various values of x
(x < 0)
-50
(x > 100)
-1
0
1
50
99 100 101
150
6
the overall result of (x < 0) && (x > 100) is always false
this condition has problems
as there is no negative value which can greater than 100
so, if the condition (x < 0) && (x > 100) is used as the
condition in a while loop or a for loop,
the loop will terminate at once and
the loop body will not be executed at all
However, if a condition that is always true is used as the
condition for a loop construct
the loop will repeat forever and
it is an infinite loop
(you’ll see an example soon)
7
Case-3 :
(x < 0) && ( x < 100 )
Now, the condition is modified to be (x < 0) && (x <100),
From Table 6.4, we note that (x <100) seems redundant, and the
given expression can be simplified as (x < 0)
Value of
x
Result of
x<0
Result of
x < 100
Result of
( (x<0) && (x<100) )
-50
(-50<0)
true
(-50<100) true
true
0
(0<0)
false
(0<100)
true
false
50
(50<0)
false
(50<100)
true
false
100
(100<0) false
(100<100) false
false
150
(150<0) false
(150<100) false
false
Table 6.4 Truth table for condition (x < 0) && (x < 100) for various values of x
(x < 100)
(x < 0)
-50
-1
0
1
50
99 100 101
150
8
The [ || ] operator
In English, we may have "x < 0" or "x > 100".
In Java, it is written as:
(x < 0) || (x > 100)
The || operator is the logical OR operator. The boolean
expressions on both sides of the || operator can be true
or false,
Table 6.5 lists the result of the || operator
Condition
Result
a
true
b
true
a || b
true
true
false
true
false
false
true
false
true
false
Table 6.5 Truth table of the [ || ] operator
9
Case-1 :
(x < 0) || ( x > 100 )
using Table 6.5, different values of variable x is listed in Table 6.6
Value of
x
Result of
x<0
Result of
x > 100
Result of
( (x<0) || (x>100) )
-50
(-50 <0)
true
(-50>100) false
true
0
(0 <0)
false
(0 >100) false
false
50
(50 <0)
false
(50 >100) false
false
100
(100 <0) false
(100>100) false
false
150
(150 <0) false
(150>100) true
true
Table 6.6 Truth table for condition (x < 0) || (x > 100) for various values of x
(x < 0)
-50
(x > 100)
-1
0
1
50
99 100 101
150
10
Equivalents codes
Two relational operators, >= and <=, can be written as two
subconditions with an || operator.
For example:
Expression
Equivalent to
x >= 0
(x > 0) || (x == 0)
x <= 100
(x < 100) || (x == 100)
The expressions in the left column are simpler and more readable than
those in the right column.
11
Case-2 :
(x > 0) || ( x < 100 )
in Table 6.7, the result is always true.
If this expression were used as the condition for an if loop, the
action part is always executed
Value of
x
Result of
x>0
Result of
x < 100
Result of
( (x>0) || (x<100) )
-50
(-50 >0)
false
(-50<100) true
true
0
(0 >0)
false
(0 <100) true
true
50
(50 >0)
true
(50 <100) true
true
100
(100 >0) true
(100<100) false
true
150
(150 >0) true
(150<100) false
true
Figure 6.7 Truth table for condition (x > 0) || (x < 100) for various values of x
(x > 0)
-50
-1
0
1
(x < 100)
50
99 100 101
150
12
Operator precedence
relational operators such as { <, >, <=, >= } take
precedence over the && operator and the || operator
so, parentheses, that enclose the sub-conditions, are not
necessary. eg.
((0 < x) && (x < 100))
is equivalent to :
(0 < x && x < 100)
It is not necessary to enclose the sub-expressions in
parentheses, but it is a good programming practice to
enclose them because it can make the expression clearer,
eg.
if ( (0 < x) && (x < 100) ) {
......
}
13
The exclusive-OR, XOR, operator [ ^ ]
In Java, we write :
(a ^ b)
in Mathematics :
(a and ~b) or (~a and b)
有你 無我, 大家 相反 就 true
Condition
Result
a
b
a^b
true
true
false
true
false
true
false
true
true
false
false
false
相 同 就 false
相 反 就 true
相 同 就 false
Table 6.5 Truth table of the short-circuited-OR operator [ || ]
14
The negation, NOT, operator [ ! ]
we can negate a boolean
boolean expression result of
expression result using a negation
x
!x
operator [ ! ]
true
false
The type of expression that follows
false
true
the ! operator must be boolean
eg.
value of
x
result of
result of
x < 0 !(x < 0 )
-5
true
false
0
false
true
5
false
true
Note :
the expression !(x < 0)
is equivalent to x >= 0
value of
x
-5
0
5
result of
result of
x < 0 (x >= 0 )
true
false
false
false
true
true
15
Self-Test 6.1
1. For variables a, b and c of type int, returns true if c is
between the value of a and b. It returns false otherwise,
provided that the value of a is less than or equal to b.
a <= c && c <= b
2. For variables a and b of type int, returns true if the sign
of the product of a and b is non-negative. It returns false
otherwise.
a * b >= 0, or
!(a >= 0 ^ b >= 0)
Note: XOR works much faster than multiplication
3. For variables a, b, c and d of type int, returns true if the
values of all variables are equal. Otherwise return false
a == b && b == c && c == d
16
Short-circuit evaluation of logical expressions
Evaluations of [ && ] and [ || ] operators in Java are short-circuit
sub-conditions on both sides of the && and || operators are
evaluated from left to right
If sub-condition on left-hand side (the first operand) determines
the result of the entire condition,
the sub-condition on its right-hand side (the second operand) is
not evaluated
otherwise, evaluate the rest sub-conditions as usual
Condition
Result
Condition
Result
a
true
true
b
true
false
a && b
true
false
a
b
a && b
true
true
true
false
false
true
false
false
false
true
false
false
false
don't care
false
Table 6.1
17
The || operator features the same short-circuit evaluation
if the first operand (the condition a) of the || operator is
true, the overall result must be true. So, no need to
evaluate the second operand (condition b)
Condition
Result
a
true
true
false
b
true
false
true
a || b
true
true
true
false
false
false
Condition
a
b
true don't care
false
true
false
false
Result
a || b
true
true
false
Table 6.5
&& short-circuits on false, while || does when true
如果考試唔記得, 就 derive them from table 6.1 & 6.5
18
How short-circuiting works ?
Consider
if (month==4 || month==6 || month==9 || month==11) {
day = 30;
}
the [ && ] and [ || ] operator are left associated, so the
above condition can be read as :
( ( ( month==4 || month==6 ) || month==9 ) || month==11 )
if the content of month
is 4 , then we have
( ( ( true || month==6 ) || month==9 ) || month==11)
by short-circuit, month == 6 is skipped, so we have
( ( true || month==9 ) || month==11)
similarly, month == 9 is skipped,
( true || month==11)
again, month == 11
is skipped, so the result is true
19
Examples
if ((a>0) && (b>0))
If a’s value is –1, then the left operand (a > 0) is false.
The overall result must be false regardless of (b > 0)
With && operator, Java will not evaluate the expression
(b>0) if (a>0) is false. This can improve performance
by avioding unnecessary evaluations
if ((a>0) || (b>0))
If a’s value 1, then the left operand (a>0) is true. The
overall result must be true regardless of (b > 0)
With || operator, Java will not evaluate the expression
(b>0) if (a>0) is true
20
Precautions
Be careful when we construct a complex Boolean
expression with short-circuit operators.
It is dangerous to import the program logic to other
programming languages. Not all programming
languages support short-circuit evaluations
Sometimes, the two operands of the operator have to be
evaluated, especially the Boolean sub-expressions with
side effects. eg.
((++i >0 ) && (++j>0))
21
Non Short-Circuit Evaluation
the OR operator [ | ]
similar to the || operator
Unlike the || operator, even the result of the first
operand of the | operator is evaluated to be true, the
second operand must be evaluated
the AND operator [ & ]
similar to the && operator
Unlike the && operator, even the result of the first
operand of the & operator is evaluated to be false, the
second operand must be evaluated
22
Precedence
Associativity
>= > < <=
Left
== !=
Left
&
Left
^
Left
|
Left
&&
Left
||
Left
Increasing Priority
Boolean
Relational
Associativity & precedence
23
Bitwise Operators
pp-18
&, | and ^ operators are also known as bitwise operators
when operands are integers.
eg
7310 =
0 1 0 0 1 0 0 1
9810 =
0 1 1 0 0 0 1 0
7310 & 9810 =
0 1 0 0 0 0 0 0
7310 =
0 1 0 0 1 0 0 1
9810 =
0 1 1 0 0 0 1 0
7310 | 9810 =
0 1 1 0 1 0 1 1
= 6410
= 10710
24
B) Advanced branching statements
pp-29
Ternary conditional operator (? : )
Condition ? Value-for-true : value-for-false
eg
public class Ternary {
public static void main ( String args[] ) {
boolean isMember=false;
double discount;
discount= isMember ? 0.8 : 0.9
System.out.println(discount);
}
}
if (isMmember) { discount = 0.8; }
else { discount=0.9; }
In this example, 0.9 is assigned to discount
25
Nested if
General format
if ( condition ) {
--// if part
} else {
--// else part
} // my current style
consider the following codes
if (
if (
if (
if (
or
if ( condition ) {
--// if part
}
else {
--// else part
} // suggested style
(age<18) && (gender ==‘M’) ) { boyCount++; }
(age<18) && (gender==‘F’) ) { girlCount++; }
(age>18) && (gender==‘M’) ) { manCount++;}
(age>18) && (gender==‘F’) ) { ladyCount++;}
// 1st statement
// <---+\
//
> rest
// <---+/
If the 1st statement is evaluated to be true,
Java still continues the rest 3 statements, because
these 4 statements are independent of each other.
This will waste processing time
26
We can use nested if/else statements to reduce
unnecessary condition evaluation :
if (age<18) {
if (gender ==‘M’) { boyCount++;}
else {girlCount++;}
} else {
if (gender==‘M’) {manCount++;}
else {ladyCount++;}
}
// outer IF
//
inner IF
//
inner ELSE
// inner IF
// inner ELSE
Now, Java only evaluates the complex boolean expression
two times, instead of four times
better performance & easier maintenance
If age is changed to 21, then
the prior version have to change all 4 statements
it is error-prone if you forget to update any 1 of the 4
27
Fig 6.5 A nested
if / else construct
pp-32
In all cases, only 1 of the 4 blocks of statements will be
evaluated
true
true
condition-2
statement(s) for
condition-1 is true
condition-2 is true
false
condition-1
false
statement(s) for
condition-1 is true
condition-2 is false
true
condition-3
statement(s) for
condition-1 is false
condition-3 is true
false
statement(s) for
condition-1 is false
condition-3 is false
28
Please use "if … else if … else if … else" to make
pp-34~37
the program more readable
if (mark>=90) { grade='A';}
// grade is set by only 1 of
else if (mark>=80) {grade='B';}
// these 5 statement blocks
else if (mark>=70) {grade='C';} // ( Fig 6.5 has 4 blocks)
else if (mark>=60) {grade='D';}
else { grade='F';}
a better version ( the suggested version is on slide-26 )
if (mark>=90) { grade='A';}
// suggestions :
else { if (mark>=80) {grade='B';}
// 1). use curly braces
else { if (mark>=70) {grade='C';} // 2). indent each blocks
else { if (mark>=60) {grade='D';}
else { grade='F';}
}
}
}
29
Dangling-else problem
pp-38
Please note that the else part always associates with the
nearest if statement.
Curly braces can avoid the dangling-else problem
eg. codes-1 will not return true for children
because Java treats codes-1 as codes-2
// codes-1
boolean isAccepted = false;
if (age>=18)
if ( gender == 'F' )
isAccepted = true;
else
isAccepted = true;
// codes-2
boolean isAccepted = false;
if ( age>=18 ) {
if ( gender == 'F' )
isAccepted = true;
else
isAccepted = true;
}
30
break in switch/case
pp-40
break statement is usually added to the end of each case statements
causes control to break out of the switch and jump to the 1st statement
following the switch statement
Without an explicit break statement, control will flow through subsequent case
statements ( eg. case 4, 6 & 9 )
public class DaysInMonth {
public static void main (String args[ ]) {
int month = Integer.parseInt(args[0]);
int days;
switch (month) {
case 2: days = 28; break;
case 4:
case 6:
case 9:
case 11: days = 30; break;
default: days = 31; break;
}
System.out.println(days); // 1st stmt
}
}
following is equivalent using
nested if/else
public class DaysInMonth2 {
public static void main (String args[ ]) {
int month = Integer.parseInt(args[0]);
int days;
if (month == 2) { days = 28; }
else if (month == 4 || month == 6 ||
month == 9 || month == 11) {
days = 30;
} else { days = 31; }
System.out.println(days);
}
}
31
placing or not to place break
in a switch/case structure
gives you greater flexibility
8 boolean variables are
declared & initialized as false
If form is 4 or 5, all 8
variables are updated to true
if form is 3, then 7 variables
will be updated to true
Otherwise, only the last 4
variables will be updated to
true
eg, when form is 1 or 2
Note : switch/case is more
elegant & easier to read, even
though it can be rewritten
using if/else
boolean takeComputer = false;
boolean takePhysics = false;
boolean takeChemistry = false;
boolean takeBiology = false;
boolean takeChinese = false;
boolean takeEnglish = false;
boolean takeMaths = false;
boolean takeMusic = false;
switch ( form ) {
case 5: case 4: takeComputer = true;
case 3:
takePhysics = true;
takeChemistry = true;
takeBiology = true;
default:
takeChinese = true;
takeEnglish = true;
takeMaths = true;
takeMusic = true;
break;
}
32
C) Advanced looping statements
pp-42
Any number of statements can be placed in the loop body
of a loop
these statements can include both
branching ( eg. if/else , switch/case ) and
looping ( eg. do/while , while , for )
while ( . . . ) {
---for ( . . . ) {
// outer loop
// inner loop A
do {
---} while ( . . . )
}
}
----
the number of levels of nested loops is unrestricted
33
Example:
public class Pattern {
// Self-test 6.6 pp-110
public static void main(String args[]) {
for (int i=0;i<5;i++) {
for (int j=0; j<=i; j++) {
System.out.print("*");
}
System.out.println(" i="+ i "); // start a new line
}
}
}
ensures the next output
starts at a new line
when i=0, inner loop iterates once; so,
when i=1, inner loop iterates twice; so,
when i=2, inner loop iterates 3 times; so,
when i=3, inner loop iterates 4 times; so,
when i=4, inner loop iterates 5 times; so,
Screen output :
* i=0
** i=1
*** i=2
**** i=3
***** i=4
keep printing on the
same line UNLESS it
exceed the screen width
print 1 "*"
print 2 "*"s
print 3 "*"s
print 4 "*"s
print 5 "*"s
34
refer to codes-1 outer loop
inner for loop can access
both i and j
outer for loop can only
access i but can't access j
declare i for
declare j for
inner loop
refer to codes-2
declaring j outside the inner
loops, both loops can access
both i and j
it is not preferable, especially
when j is changed in both
outer and inner loops,
because logic is complicated
and the program is more
difficult to read & maintain.
public class Pattern {
// codes-1 (self test 6.6)
public static void main(String args[]) {
for ( int i=0; i<5; i++) {
// outer
for ( int j=0; j<=i; j++) {
// inner
System.out.print("*");
}
System.out.println(" i="+ i");
}
}
}
public class Pattern1 {
// codes-2
public static void main(String args[]) {
for (int i=0; i<5; i++) {
declare j for
int j;
inner loop
for (j=0; j<=i; j++) {
j *= 2;
System.out.print("*");
}
System.out.println(" i="+i+", j="+j);
}
j is accessible
}
by outer loop
}
Screen * i=0 j=1
output ** i=1 j=3
** i=2 j=3
*** i=3 j=7
*** i=4 j=7
35
Revisiting Class & Driver concept
public class ObjectWithNestedLoop {
public void showVariablesInNestedLoop (
int outerLimit, int innerLimit ) {
int count = 0;
for (int i=0; i < outerLimit; i++) {
for (int j=0; j < innerLimit; j++) {
count++;
System.out.println(
count + " : i=" + i + " & j=" + j);
}
}
System.out.println(
"Total number of iterations = "+ count
);
}
pp 45~46
public class TestObjectWithNestedLoop {
public static void main(String args[]) {
if (args.length < 2) {
System.out.println(
"Usage: java TestObjectWithNestedLoop"
+ " <outer limit> <inner limit>");
}
else {
ObjectWithNestedLoop objectWithNL
= new ObjectWithNestedLoop();
int outerLimit=Integer.parseInt(args[0]);
int innerLimit=Integer.parseInt(args[1]);
objectWithNL.showVariablesInNestedLoop
(outerLimit, innerLimit);
}
}
}
}
36
Testing on " TestObjectWithNestedLoop "
N:\unit-6>java TestObjectWithNestedLoop 3
Usage: java TestObjectWithNestedLoop <outer limit> <inner limit>
java TestObjectWithNestedLoop 2 3
1 : i=0 & j=0
2 : i=0 & j=1
3 : i=0 & j=2
4 : i=1 & j=0
5 : i=1 & j=1
6 : i=1 & j=2
Total number of iterations = 6
java TestObjectWithNestedLoop 3 2
1 : i=0 & j=0
2 : i=0 & j=1
3 : i=1 & j=0
4 : i=1 & j=1
5 : i=2 & j=0
6 : i=2 & j=1
Total number of iterations = 6
ensure each cases
are encountered
java TestObjectWithNestedLoop 3 0
Total number of iterations = 0
java TestObjectWithNestedLoop 0 3
Total number of iterations = 0
java TestObjectWithNestedLoop 1 1
1 : i=0 & j=0
Total number of iterations = 1
java TestObjectWithNestedLoop 1 2
1 : i=0 & j=0
Inner loop was called once &
2 : i=0 & j=1
it iterated twice
Total number of iterations = 2
java TestObjectWithNestedLoop 2 1
1 : i=0 & j=0
Inner loop was called twice;
each time iterated once
2 : i=1 & j=0
Total number of iterations = 2
37
Break Vs Continue
pp 52
The break statement,
is usually used in switch/case statements
can be used in the loop body
When break statement is executed, the program control
jumps to the statement after the loop body,
i.e. break the loop
The continue statement
the program control
jumps to the end of the loop and then
go back to the condition checking and continues
38
Table 6.14 Positions of continue statement
do/while loop
do {
..
if (condition)
{
..
continue;
}
else {
..
continue;
}
..
} while ( .. ) ;
for loop
for ( .. ; .. ; .. ) {
..
if (condition)
{
..
continue;
}
else {
..
continue;
}
..
}
pp 53
while loop
while ( .. ) {
..
if (condition)
{
..
continue;
}
else {
..
continue;
}
..
}
39
Table 6.15 break vs continue
break
users
pp 54
continue
Can be used in looping
Can be used in all
structures only
looping structures &
switch/case statements
effects quit the loop or
switch/case statement
Immediately &
unconditionally
1. Skips the remaining
statements in loop body
2. execute the update part
of the for loop, &
3. check loop condition
to determine if the loop
continues or not
40
Example
class ContinueAndBreak {
public static void main (String args[]) {
int i, max=7;
for (i=1; i<=max; i++) {
if (i==4) { break; }
System.out.println("i = "+i);
}
System.out.println("break => ends &
don't print 4 & others");
for (i=1; i<=max; i++) {
if (i==4) { continue; }
System.out.println("i = "+i);
}
System.out.println("continue => skip
4 & resume job");
}
}
// adopted from Kwan Ying's example
i=1
i=2
i=3
break => ends & don't print 4 & others
i=1
i=2
i=3
i=5
i=6
i=7
continue => skip 4 & resume job
Screen Output
41
D) Sorting
pp 59
Binary search requires the elements must be ordered
such as ascending order of numeric values
Such an ordering operation is known as sorting
For example, if you have an square object with element
type of int as follows,
12
32
4
87
22
it is expected after sorting, the contents of the square
elements have become
4
12
22
32
87
42
Insertion sort
sorted
unsorted
Step1: Separate the sorting scope
into 2 regions :
sorted, unsorted
Step 2: Copy the first element, such
as A, of the unsorted region
to a variable storage
Step 3: Start from the last number of
the sorted region, compare
with the number in the
variable storage .
If it is greater than A, then it
moves downward.
Step 4: Insert the number A to the
empty space in the
sorted region
sorted
unsorted
0
12
32
4
12
storage
32
32
4
22
sorted
unsorted
32
87
87
4
pp 61~65
22
12
12
32
4
4
32
4
12
sorted
unsorted
4
87
87
22
12
32
22
87
87
22
4
4
4
12
12
12
32
32
22
87
22
22
32
87
22
32
22
87
43
public class InsertionSorter2 {
pp 71
public static void sort(int[] numbers) {
for (int sorted = 0; sorted < numbers.length - 1; sorted++) {
System.out.print("DEBUG: sorted region = ");
for (int i=0; i <= sorted; i++) { System.out.print(numbers[i] + "\t"); }
System.out.print("\nDEBUG: unsorted region = ");
for (int i=sorted + 1; i < numbers.length; i++) { System.out.print(numbers[i] + "\t");}
System.out.println();
int storage = numbers[sorted + 1];
System.out.println("DEBUG: Number to be moved = " + storage);
int forCompare = sorted;
while (forCompare >= 0 && numbers[forCompare] > storage) {
numbers[forCompare + 1] = numbers[forCompare];
System.out.println("DEBUG: " + numbers[forCompare]
+ " is copied to the next element");
forCompare--;
}
numbers[forCompare + 1] = storage;
System.out.println("DEBUG: " + storage + " is stored in numbers["
+ (forCompare + 1) + "]\n");
}
}
}
44
public class TestInsertionSorter2 {
public static void main(String args[]) {
if (args.length == 0) {
System.out.println( "Usage: java TestInsertionSorter num1 num2 ..."); }
else {
int[] numbers = new int[args.length];
for (int i=0; i < args.length; i++) { numbers[i] = Integer.parseInt(args[i]) }
InsertionSorter2 sorter = new InsertionSorter2();
sorter.sort(numbers);
// Sort numbers using square object
System.out.println("Sorted numbers:"); // Show the sorted numbers on screen
for (int i=0; i < numbers.length; i++) { System.out.print(numbers[i] + "\t"); }
System.out.println();
}
}
}
45
Screen output
java TestInsertionSorter2 12 32 4 87 22
DEBUG: sorted region = 12
DEBUG: unsorted region = 32 4
87
22
DEBUG: Number to be moved = 32
DEBUG: 32 is stored in numbers[1]
pp 72
DEBUG: sorted region = 12
32
DEBUG: unsorted region = 4
87
22
DEBUG: Number to be moved = 4
DEBUG: 32 is copied to the next element
DEBUG: 12 is copied to the next element
DEBUG: 4 is stored in numbers[0]
DEBUG: sorted region = 4
12
32
DEBUG: unsorted region = 87 22
DEBUG: Number to be moved = 87
DEBUG: 87 is stored in numbers[3]
DEBUG: sorted region = 4
12
32
DEBUG: unsorted region = 22
DEBUG: Number to be moved = 22
DEBUG: 87 is copied to the next element
DEBUG: 32 is copied to the next element
DEBUG: 22 is stored in numbers[2]
Sorted numbers:
4
12
22
32
87
87
46
E) Multidimensional Arrays
pp 77
It is an array of array Objects
Declaration Syntax:
eg.
type[][] <variable>
// variation 1
type <variable>[][]
// variation 2
int [] [] a = new int [5] [10];
Alternatively
int [] [] a = new int[5][];
a[0] = new int[10];
a[1] = new int[10];
a[2] = new int[10];
a[3] = new int[10];
a[4] = new int[10];
47
Example-1
double[][] threeByFourTable;
threeByFourTable = new double[3][4];
[0]
threeByFourTable
[1]
[2]
3
48
square[0] [0]
square[0]
8
[0]
3
[1]
4
[2]
pp 80~83
3
[0]
square
1
square[0].length
square[1]
[1]
[2]
3
square[1] [1]
5
9
3
square[2] [0]
Example2
int [] [] square = { {8,3,4}, {1,5,9}, {6,7,2} };
6
7
square[2]
2
3
49
Matrix Manipulations ( out syllabus )
Given : two 2x2 matrix A and B
b11 b12
a11 a12
B
A
b21 b22
a21 a22
Addition of
Product
of Matrix
A and B
A and B
pp 82
Identify Matrix,
diagonal
elements are all
'1's; others are '0'
1 0
I
0 1
a11 a12 b11 b12
A B
a21 a22 b21 b22
a11 * b11 a12 b12
a21 b21 a22 b22
a11 a12 b11 b12
*
A * B
a21 a22 b21 b22
a11 * b11 a12 * b21 a11 * b12 a12 * b22
a21 * b11 a22 * b21 a21 * b12 a22 * b22
50
pp 83
public class MatrixHandler {
public void showMatrix(double[][] matrix) {
for (int row=0; row < matrix.length; row++) {
for (int col=0; col < matrix[row].length; col++)
{ System.out.print(matrix[row][col] + "\t"); }
System.out.println();
}
}
public double sumElements(double[][] matrix){
double total = 0.0;
public double[][] createIdentityMatrix(int rank){
double[][] matrix = new double[rank][rank];
for (int i=0; i < rank; i++) {
matrix[i][i] = 1.0;
}
return matrix;
}
public double[][] multiply(
double[][] a, double[][] b) {
double[][] c = new
double[a.length][b[0].length];
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < b[0].length; col++) {
c[row][col] = 0.0;
for (int i=0; i < b.length; i++) {
c[row][col] += a[row][i] * b[i][col];
}
}
}
return c;
}
// Add the value in each row and column
for (int row=0; row < matrix.length; row++){
for (int col=0; col < matrix[row].length; col++)
{ total += matrix[row][col]; }
}
return total;
}
// cont'd on the right
}
51
1 2 5 6
public class TestMatrixHandler2 {
*
A * B
public static void main(String args[]) {
3 4 7 8
double[][] a = { { 1, 2}, { 3, 4} };
1* 5 2 * 7 1* 6 2 * 8
double[][] b = { {5, 6}, { 7, 8} };
3 * 5 4 * 7 3 * 6 4 * 8
MatrixHandler handler = new MatrixHandler();
The matrix A:
System.out.println("The matrix A:");
1.0 2.0
handler.showMatrix(a);
3.0 4.0
System.out.println("\nThe matrix B:");
handler.showMatrix(b);
The matrix B:
double[][] c = handler.multiply(a, b);
5.0 6.0
System.out.println(
7.0 8.0
"\nThe product matrix of matrices A and B:");
handler.showMatrix(c);
The product matrix of matrices A and B:
System.out.println(
19.0 22.0
"\nSum of all elements in matrix product="
43.0 50.0
+ handler.sumElements(c));
double[][] d = handler.createIdentityMatrix(4);
Sum of all elements in matrix product=134.0
System.out.println("\nIdentity matrix of rank 4");
handler.showMatrix(d);
Identity matrix of rank 4
}
1.0 0.0 0.0 0.0
}
0.0 1.0 0.0 0.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
1.0
Screen Output
52
Ragged ( 不平的 ) Arrays
pp 87
Java implements 2-dimensional arrays as 2 levels of 1-dimension
arrays
as the 2nd level arrays objects are mutually independent, so they can
have different size
so it is called ragged arrays
Example
int[][] ragged = new int[3][];
int[0] = new int[5];
int[1] = new int[2];
int[2] = new int[4];
[0]
ragged
[1]
[2]
3
53
F) Recursion — an advanced control structure
pp 90
Recursion is a problem-solving technique that, if given a
problem, is resolved to another identical problem but with
a smaller size.
Such an approach is repeated until a well-defined answer
is obtained.
Usually, a method is recursive if it calls itself either
directly or indirectly.
Recursion is considered as a more elegant and simpler
solutions.
But it also incurs larger memory and time overhead.
54
Self-test 6.9 : summation of N numbers
n
given sumn 1 x 1 2 3 n 1 n
n 1
1 x n
sumn 1 n or n sumn 1
base condition is
sum (1 ) = 1
public class Summation {
public int sum ( int n ) {
if ( n == 1 )
return 1 ;
else
return ( n + sum ( n-1 ) ) ;
}
}
public class TestSummation {
public static void main(String args[]) {
int n = Integer.parseInt(args[0]);
Summation mySum = new Summation( );
System.out.println( mySum.sum (n) );
}
}
55
Java TestSummation 3
The number 6 is returned
to the driver program
6
public int sum ( int n ) {
if ( n == 1 ) return 1 ;
else
return ( n + sum ( n-1 ) ) ;
}
3
3
2
public int sum ( int n ) {
if ( n == 1 ) return 1 ;
else
return ( n + sum ( n-1 ) ) ;
}
2
1
1
public int sum ( int n ) {
if ( n == 1 ) return 1 ;
else
return ( n + sum ( n-1 ) ) ;
}
56