Module - 2
Module - 2
•
School of Mechanical Engineering
Course Content
Conditional Control Statements in Java
Conditional control statements in java
Relational Operators
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
}
+ " for the circle of radius "
+ radius + " is " + area);
}
Note
Example
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, print HiFive. If the number is divisible
by 2, print HiEven.
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
|| or logical disjunction
true false !(age > 18) is false, because (age > 18) is true.
false false false (age <= 18) && (weight < 140) is false, because both
false
true false (age > 18) && (weight > 140) is false, because (weight
true
true true (age > 18) && (weight >= 140) is true, because both
false true true (age > 34) || (weight <= 140) is true, because (age > 34)
is false, but (weight <= 140) is true.
true
true false (age > 14) || (weight >= 150) is false, because
true
true true
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)
false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false
false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false
true
true false (age > 14) ^ (weight > 140) is true, because (age > 14) is
false
true true
Examples
Here is a program that checks whether a number is divisible by 2
and 3, whether a number is divisible by 2 or 3, and whether a
number is divisible by 2 or 3 but not both:
Examples
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " + TestBooleanOperators
((number % 2 == 0) ^ (number % 3 == 0))); Run
Companion
Website
The & and | Operators
Statements break;
case 3: compute taxes for head of
household;
break;
default: System.out.println("Errors: invalid
status");
System.exit(1);
}
switch Statement Flow Chart
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
case valueN: statement(s)N;
The resulting statements in the
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
of each case in order to terminate case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement
is not present, the next case case value2: statement(s)2;
statement will be executed. break;
…
case valueN: statement(s)N;
The default case, which is
break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the }
specified cases matches the
switch-expression.
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
animation
Trace switch statement
Suppose day is 2:
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Match case 2
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 3
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 4
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 5
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Encounter break
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Exit the statement
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Sample
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
}
}
Problem: Chinese Zodiac
ChineseZodiac Run
Conditional Expressions
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Conditional Operator, cont.
boolean-expression ? exp1 : exp2
Operator Precedence
• ()
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule
and the associativity rule.
RepeatAdditionQuiz Run
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number. For each user
input, the program tells the user whether the input is too
low or too high, so the user can choose the next input
intelligently. Here is a sample run:
GuessNumberOneTime Run
GuessNumber Run
Problem: An Advanced Math Learning Tool
SubtractionQuizLoop Run
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel value.
SentinelValue Run
Caution
Don’t use floating-point values for equality checking in a
loop control. Since floating-point values are
approximations for some values, using them could result
in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8
+ ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) {
System.out.println(
// loop body;
Statement(s); "Welcome to Java!");
} }
animation
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
Recommendations
Use the one that is most intuitive and comfortable for
you. In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if
the number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has to
be executed before testing the continuation condition.
Nested Loops
Problem: Write a program that uses nested for
loops to print a multiplication table.
MultiplicationTable Run
Minimizing Numerical Errors
FutureTuition Run
Problem: Predicating the Future Tuition
double tuition = 10000; int year = 0 // Year 0
tuition = tuition * 1.07; year++; // Year 1
tuition = tuition * 1.07; year++; // Year 2
tuition = tuition * 1.07; year++; // Year 3
...
Case Study: Converting Decimals to
Hexadecimals
Hexadecimals are often used in computer systems programming (see
Appendix F for an introduction to number systems). How do you
convert a decimal number to a hexadecimal number? To convert a
decimal number d to a hexadecimal number is to find the
hexadecimal digits hn, hn-1, hn-2, ... , h2, h1, and h0 such that
circleArea / squareArea = / 4.
can be approximated as 4 *
numberOfHits / numberOfTrials
MonteCarloSimulation Run
Using break and continue
Examples for using the break and continue
keywords:
TestBreak.java
TestBreak Run
TestContinue.java
TestContinue Run
break
continue
Guessing Number Problem Revisited
GuessNumberUsingBreak Run
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward.
The words “mom,” “dad,” and “noon,” for instance, are all
palindromes.
The problem is to write a program that prompts the user to enter a
string and reports whether the string is a palindrome. One solution is
to check whether the first character in the string is the same as the last
character. If so, check whether the second character is the same as the
second-to-last character. This process continues until a mismatch is
found or all the characters in the string are checked, except for the
middle character if the string has an odd number of characters.
Palindrome Run
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater
than 1 is prime if its only positive divisor is 1 or itself. For example,
2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
• For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
• Determine whether a given number is prime.
• Count the prime numbers.
• Print each prime number, and print 10 numbers per line.
PrimeNumber Run
Single-Dimensional Arrays
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
Example:
myList = new double[10];
arrayRefVar.length
For example,
myList.length returns 10
Default Values
When an array is created, its elements are
assigned the default value of
arrayRefVar[index];
Using Indexed Variables
After an array is created, an indexed variable
can be used in the same way as a regular
variable. For example, the following code adds
the value in myList[0] and myList[1] to myList[2].
i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
Finding the largest element
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Anonymous array
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array.
Such array is called an anonymous array.
Pass By Value
Java uses pass by value to pass arguments to a method. There are
important differences between passing a value of variables of
primitive data types and passing arrays.
TestPassArray Run
Example, cont.
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
list
return result;
} result
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) { Assign list[0] to result[5]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 1 and j = 4
public static int[] reverse(int[] list) { Assign list[1] to result[4]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 2 and
public static int[] reverse(int[] list) { j becomes 3
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=2) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 3 and
public static int[] reverse(int[] list) { j becomes 2
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=3) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 4 and
public static int[] reverse(int[] list) { j becomes 1
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=4) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 5 and
public static int[] reverse(int[] list) { j becomes 0
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=5) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 6 and
public static int[] reverse(int[] list) { j becomes -1
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=6) < 6 is false. So exit
public static int[] reverse(int[] list) { the loop.
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
list 1 2 3 4 5 6
list2
result 6 5 4 3 2 1
Problem: Counting Occurrence of Each
Letter
• Generate 100 lowercase letters randomly and assign to an array of
characters.
• Count the occurrence of each letter in the array.
CountLettersInArray Run
Variable-Length Arguments
You can pass a variable number of arguments of the same
type to a method.
VarArgsDemo Run
Searching Arrays
Searching is the process of looking for a specific element in
an array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search
and binary search.
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in the
array list. The method continues to do so until the key
matches an element in the list or the list is exhausted
without a match being found. If a match is made, the
linear search returns the index of the element in the
array that matches the key. If no match is found, the
search returns -1.
animation
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
animation
Linear Search Animation
http://www.cs.armstrong.edu/liang/animation/web/
LinearSearch.html
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
Binary Search
Key List
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
animation
Binary Search Animation
http://www.cs.armstrong.edu/liang/animation/web/
BinarySearch.html
Binary Search, cont.
Binary Search, cont.
Binary Search, cont.
The binarySearch method returns the index of the
element in the list that matches the search key if it is
contained in the list. Otherwise, it returns
-insertion point - 1.
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " +
java.util.Arrays.binarySearch(list, 11));
Return is 4
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +
java.util.Arrays.binarySearch(chars, 't')); Return is –4 (insertion point
is 3, so return is -3-1)
For the binarySearch method to work, the array must be pre-sorted in increasing
order.
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces a simple,
intuitive sorting algorithms: selection sort.
Selection Sort
Selection sort finds the smallest number in the list and places it first. It then finds
the smallest number remaining and places it second, and so on until the list
contains only a single number.
animation
Selection Sort Animation
http://www.cs.armstrong.edu/liang/animation/web/
SelectionSort.html
From Idea to Solution
for (int i = 0; i < list.length; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i+1..listSize-1]
}
...
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i+1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
java Calculator 2 + 3
java Calculator 2 - 3
Calculator java Calculator 2 / 3
Run java Calculator 2 . 3
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
222
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays
double[][] x;
223
Two-dimensional Array Illustration
matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
224
Declaring, Creating, and Initializing Using Shorthand Notations
225
Lengths of Two-dimensional Arrays
226
Lengths of Two-dimensional Arrays, cont.
array[4].length ArrayIndexOutOfBoundsException
227
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
{5} matrix[4].length is 1
};
228
Ragged Arrays, cont.
229
Processing Two-Dimensional Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
230
Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}
231
Initializing arrays with random values
232
Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
233
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
234
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}
235
Random shuffling
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}
236
Problem: Grading Multiple-Choice Test
237
Problem: Finding Two Points Nearest to Each Other
238
What is Sudoku?
http://www.cs.armstrong.edu/
liang/animation/web/Sudoku.html
239
Every row contains the numbers 1 to 9
240
Every column contains the numbers 1 to 9
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
241
Every 3×3 box contains the numbers 1 to 9
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
242
Checking Whether a Solution Is Correct
PassTwoDimensionalArray Run
243
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.
The way to declare two-dimensional array variables and
create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3.
244
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}
};
245
Problem: Calculating Total Scores
Objective: write a program that calculates the total score for
students in a class. Suppose the scores are stored in a three-
dimensional array named scores. The first index in scores refers
to a student, the second refers to an exam, and the third refers
to the part of the exam. Suppose there are 7 students, 5 exams,
and each exam has two parts--the multiple-choice part and the
programming part. So, scores[i][j][0] represents the score on the
multiple-choice part for the i’s student on the j’s exam. Your
program displays the total score for each student.
246
Problem: Weather Information
Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the data
for the past ten days in a text file named weather.txt. Each
line of the file consists of four numbers that indicate the
day, hour, temperature, and humidity. Your task is to write
a program that calculates the average daily temperature
and humidity for the 10 days.
247
Problem: Guessing Birthday
Listing 4.3, GuessBirthday.java, gives a program that
guesses a birthday. The program can be simplified by
storing the numbers in five sets in a three-dimensional
array, and it prompts the user for the answers using a
loop.
248
Problem:
References:
• https://www.javatpoint.com/
• https://www.geeksforgeeks.org/
• https://www.w3schools.com/
• https://www.educba.com/
• Y. Daniel Liang, Intro to Java Programming, Pearson
Education India
Thank You All