Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue: the loop skips this iteration right after a continue statement is executed. In practice, jump statements in loops should be conditioned. Zheng-Liang Lu Java Programming 136 / 167
Example: Primality Write a program which determines if the input integer is a prime number. Let x > 1 be any natural number. Then x is said to be a prime number if x has no positive divisors other than 1 and itself. It is then straightforward to check if it is prime by dividing x by all natural numbers smaller than x. For speedup, you can divide x by only numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 137 / 167
1... 2 Scanner input = new Scanner(System.in); 3 System.out.println("Enter x > 2?"); 4 int x = input.nextint(); 5 boolean isprime = true; 6 input.close(); 7 8 for (int y = 2; y < Math.sqrt(x); y++) { 9 if (x % y == 0) { 10 isprime = false; 11 break; 12 } 13 } 14 15 if (isprime) { 16 System.out.println("Prime"); 17 } else { 18 System.out.println("Composite"); 19 } 20... Zheng-Liang Lu Java Programming 138 / 167
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price ( 1 to exit):"); 4 curritem = input.nextint(); 5 if (curritem >= 0) { 6 amount += curritem; 7 } else if (curritem == 1) { 8 System.out.println("Total = " + amount); 9 break; 10 } 11 } 12... Zheng-Liang Lu Java Programming 139 / 167
Another Example Write a program which determines the holding years for an investment doubling its value. Let curr be the current amount, goal be the goal of this investment, and r be the annual interest rate. Then this investment should take at least n years so that the balance of the investment can double its value. Recall that the compounding formula is given by curr = curr (1 + r/100). Zheng-Liang Lu Java Programming 140 / 167
1... 2 int r = 18; // 18% 3 int curr = 100; 4 int goal = 200; 5 6 int years = 0; 7 while (curr <= goal) { 8 curr = (1 + r / 100.0); 9 years++; 10 } 11 12 System.out.println("Years = " + years); 13 System.out.println("Balance = " + curr); 14... Zheng-Liang Lu Java Programming 141 / 167
1... 2 int years = 0; // should be declared here; scope issue 3 for (; curr <= goal; years++) { 4 curr = (1 + r / 100); 5 } 6... 1... 2 int years = 1; // check this initial value 3 for (; true; years++) { 4 curr = (1 + r / 100); 5 if (curr >= goal) break; 6 } 7... A for loop can be an infinite loop by setting true or simply leaving empty in the condition statement. An infinite for loop with an if-break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 142 / 167
Equivalence: while and for Loops (Concluded) In general, a for loop may be used if the number of repetitions is known in advance. If not, a while loop is preferred. Zheng-Liang Lu Java Programming 143 / 167
Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. Zheng-Liang Lu Java Programming 144 / 167
Example Multiplication table Write a program which displays the multiplication table. Zheng-Liang Lu Java Programming 145 / 167
Formatting Console Output You can use System.out.printf () to display formatted output on the console. 1... 2 double amount = 1234.601; 3 double interestrate = 0.00528; 4 double interest = amount interestrate; 5 System.out.printf("Interest = %4.2f", interest); 6... Zheng-Liang Lu Java Programming 146 / 167
By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 147 / 167
Multiple Items to Print Items must match the format specifiers in order, in number, and in exact type. If an item requires more spaces than the specified width, the width is automatically increased. By default, the output is right justified. You may try the plus sign (+), the minus sign (-), and 0 in the middle of format specifiers. Say % + 8.2f, % 8.2f, and %08.2f. Zheng-Liang Lu Java Programming 148 / 167
1... 2 public static void main(string[] args) { 3 for (int i = 1; i <= 9; ++i) { 4 for (int j = 1; j <= 9; ++j) { 5 System.out.printf("%3d", i j); 6 } 7 System.out.println(); 8 } 9 } 10... Zheng-Liang Lu Java Programming 149 / 167
Exercise: Coupled Loops Zheng-Liang Lu Java Programming 150 / 167
1 public class PrintStarsDemo { 2 public static void main(string[] args) { 3 // case (a) 4 for (int i = 1; i <= 5; i++) { 5 for (int j = 1; j <= i; j++) { 6 System.out.printf(" "); 7 } 8 System.out.println(); 9 } 10 } 11 } Zheng-Liang Lu Java Programming 151 / 167
Analysis of Algorithms First, there may exist some algorithms for the same problem, which are supposed to be correct. Then we compare these algorithms. The first question is, Which one is more efficient? (Why?) We focus on the growth rate of the running time or space requirement as a function of the input size n, denoted by f (n). Zheng-Liang Lu Java Programming 152 / 167
O-notation 1 In math, O-notation describes the limiting behavior of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions. f (n) O(g(n)) as n if and only if there is a constant c > 0 and a real number n 0 such that f (n) c g(n) n n 0. (1) Note that O(g(n)) is a set featured by some simple function g(n). Hence f (n) O(g(n)) is equivalent to say that f (n) is one instance of O(g(n)). 1 See any textbook for data structures and algorithms. Zheng-Liang Lu Java Programming 153 / 167
For example, 8n 2 3n + 4 O(n 2 ) (tight bound). We say 8n 2 3n + 4 O(n 3 ) and 8n 2 3n + 4 / O(n). Zheng-Liang Lu Java Programming 154 / 167
Growth Rates for Fundamental Functions 2 2 See Table 4.1 and Figure 4.2 in Goodrich and etc, p. 161. Zheng-Liang Lu Java Programming 155 / 167
All in all, O-notation describes the asymptotic 3 upper bound of complexity of the algorithm. So O-notation is widely used to classify algorithms by how they respond to changes in input size. 4 Time complexity Space complexity 3 The asymptotic sense is that the input size n grows toward infinity. 4 Actually, there are Θ, θ, o, Ω, and ω which are used to classify algorithms. Zheng-Liang Lu Java Programming 156 / 167
References https://en.wikipedia.org/wiki/game_complexity https://en.wikipedia.org/wiki/p_versus_np_problem Zheng-Liang Lu Java Programming 157 / 167
1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 158 / 167
Arrays An array stores a large collection of data which is of the same type. 1... 2 // assume the size variable exists above 3 T[] A = new T[size]; 4 // this creates an array of T type, referenced by A 5... T can be any data type. This statement comprises two parts: Declaring a reference Creating an array Zheng-Liang Lu Java Programming 159 / 167
Variable Declaration for Arrays In the left-hand side, it is a declaration for an array variable, which does not allocate real space for the array. In reality, this variable occupies only a certain space for the reference to an array. 5 If a reference variable does not refer to an array, the value of the variable is null. 6 In this case, you cannot assign elements to this array variable unless the array object has already been created. type. 5 Recall the stack and the heap in the memory layout. 6 Moreover, this holds for any reference variable. For example, the Scanner Zheng-Liang Lu Java Programming 160 / 167
Creating A Real Array All arrays of Java are objects. As seen before, the new operator returns the memory address of that object. Recall that the type of reference variables must be compatible to that of the array object. The variable size must be a positive integer for the number of elements. Note that the size of an array cannot be changed after the array is created. 7 7 You can try the ArrayList class. See any textbook for data structures. Zheng-Liang Lu Java Programming 161 / 167
Consider this array: 1 int[] A = new int[3]; Arrays in Memory The array is allocated contiguously in the memory. Note that all arrays are zero-based indexing. 8 (Why?) So we have A[0], A[1], and A[2]. 8 Same in C, C++, and more languages. Zheng-Liang Lu Java Programming 162 / 167
Array Initializer Arrays can be initialized when they are declared. When an array is created, all elements are assigned by default: 0 for all numeric primitive data types \u0000 for char type false for boolean type An array can also be initialized by enumerating all the elements. For example, 1 int[] A = {1, 2, 3}; Note that there is no need to use new if enumeration is used. Zheng-Liang Lu Java Programming 163 / 167
Processing Arrays When processing array elements, we often use a for loop. Since the size of the array is known, it is natural to use a for loop to manipulate the array. For all arrays, they have a field called length which records the size of this array. For example, use A.length to get the size of A. Zheng-Liang Lu Java Programming 164 / 167
Examples Initializing arrays with input values 1... 2 // let x be an integer array with a certain size 3 for (int i = 0; i < A.length; ++i) { 4 A[i] = input.nextint(); 5 } 6... Initializing arrays with random values 1... 2 for (int i = 0; i < A.length; ++i) { 3 A[i] = (int) (Math.random() 10); 4 } 5... Zheng-Liang Lu Java Programming 165 / 167
Displaying arrays 1... 2 for (int i = 0; i < A.length; ++i) { 3 System.out.printf("A[%d] = %d\n", i, A[i]); 4 } 5... Summing all elements 1... 2 int sum = 0; 3 for (int i = 0; i < A.length; ++i) { 4 sum += A[i]; 5 } 6... Zheng-Liang Lu Java Programming 166 / 167
Finding the extreme values 1... 2 int max = A[0]; 3 int min = A[0]; 4 for (int i = 1; i < A.length; ++i) { 5 if (max < A[i]) max = A[i]; 6 if (min > A[i]) min = A[i]; 7 } 8... How about the location of the extreme values? Zheng-Liang Lu Java Programming 167 / 167