Example. Password generator
|
|
- Suzanna Washington
- 6 years ago
- Views:
Transcription
1 Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that a character is encoded using an integer. How to generate these characters randomly? Zheng-Liang Lu Java Programming 193 / 249
2 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A ) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a ) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( 9 0 ) + 0 ); 12 } Zheng-Liang Lu Java Programming 194 / 249
3 public static void main (String[] args) { 3 System.out.println("Generating a password..."); 4 // def: 0 > upper case, 1 > lower case, 2 > numbers 5 int type; 6 for (int i = 1; i <= 10; ++i){ 7 type = (int)((math.random() 10) % 3); 8 switch (type) { 9 case 0: 10 System.out.printf("%c", getrandomuppercaseletter()); 11 break; 12 case 1: 13 System.out.printf("%c", getrandomlowercaseletter()); 14 break; 15 case 2: 16 System.out.printf("%c", getrandomdigitalcharacter()); 17 break; 18 } 19 } 20 } Zheng-Liang Lu Java Programming 195 / 249
4 Abstraction Abstraction is a technique for managing complexity of computer systems. Higher level of abstraction hides the detail at lower levels, and provides the interfaces only. The programmer works with the well-defined interface and can add additional levels of functionality that would otherwise be too complex to handle. For example, no need to know how System.out.println() works. Zheng-Liang Lu Java Programming 196 / 249
5 Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 197 / 249
6 Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 198 / 249
7 Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. It is encapsulation. 1 1 Recall that object-oriented programming languages fulfill encapsulation, inheritance, and polymorphism. Zheng-Liang Lu Java Programming 199 / 249
8 Divide and Conquer When developing a program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose the original problem into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. Pros: easier to write, reuse, debug, test, modify, maintain, and better facilitating teamwork For most problems, do not write the entire program at once. Be aware that sitting in front of the computer is the last thing when programming. Zheng-Liang Lu Java Programming 200 / 249
9 Recursion 2 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is essentially repetition without a loop. 2 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 201 / 249
10 Try Fractal. Zheng-Liang Lu Java Programming 202 / 249
11 Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. 3 For example, 5! = 5 4! = 5 (4 3!) = 5 (4 (3 2!)) = 5 (4 (3 (2 1))) = 5 (4 (3 2)) = 5 (4 6) = 5 24 = 120. Can you find the pattern? 3 Note that 0! = 1. Zheng-Liang Lu Java Programming 203 / 249
12 Zheng-Liang Lu Java Programming 204 / 249
13 Write a program which determines 10! static int factorial(int n) { 3 if (n!= 0) { 4 return n factorial(n 1); 5 } else { 6 return 1; // base condition 7 } 8 } 9... Note that there must be a base condition in recursion. So, can you replace a recursive method by a loop? Zheng-Liang Lu Java Programming 205 / 249
14 Equivalence: Recursion Replaced by Loops int x = 1; 3 for (int i = 10; i > 0; i = i 1) { 4 x = i; 5 } 6... One intriguing question is, Can we always turn a recursive method into an iterative one? Yes, theoretically. 4 4 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 206 / 249
15 In Practice Recursion bears substantial overhead. So, the recursive algorithm may execute a bit more slowly than the iterative equivalent. Besides, a deeply recursive method depletes the call stack, which is limited, and causes a exception fast. 5 The decision whether to use recursion or iteration should be based on the nature of, and your understanding of, the problem you are trying to solve. 5 Stack overflow. Zheng-Liang Lu Java Programming 207 / 249
16 Zheng-Liang Lu Java Programming 208 / 249
17 Exercise Fibonacci numbers Write a program which determines the first 10 Fibonacci numbers. A sequence F n of Fibonacci numbers is defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Zheng-Liang Lu Java Programming 209 / 249
18 Zheng-Liang Lu Java Programming 210 / 249
19 static int fibrecursive(int n) { 3 if (n == 1 n == 0) { 4 return (n == 1)? 1 : 0; 5 } else { 6 return fib(n 1) + fib(n 2); 7 } 8 } 9... The recursive implementation of fib is very simple and straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. 6 Can you find a linear recursion for Fibonacci numbers? 6 fib is an exponential-time algorithm while factorial is a linear-time algorithm. (Why?) Zheng-Liang Lu Java Programming 211 / 249
20 You can try an iterative approach for Fibonacci numbers static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n < 2) { 5 return (n == 1)? y : x; 6 } else { 7 for (int i = 0; i < n; ++i){ 8 int tmp = x + y; 9 x = y; 10 y = tmp; 11 } 12 return y; 13 } 14 } Zheng-Liang Lu Java Programming 212 / 249
21 Problem Set Exercise 5.1 (Greatest common divisor) Write a program which receives two positive integers and returns the greatest common divisor using a recursive approach. Exercise 5.2 (Towers of Hanoi) Write a program which performs the classical problem, Towers of Hanoi, and shows the movements of disks. Zheng-Liang Lu Java Programming 213 / 249
22 Zheng-Liang Lu Java Programming 214 / 249
23 1 class Lecture6 { 2 3 "Arrays" 4 5 } 6 7 / References 8 [1] Ch. 6 and 7 in YDL 9 / Zheng-Liang Lu Java Programming 215 / 249
24 Arrays An array variable can reference a large collection of data of the same type. 1 elementtype[] arrayname; // Java convention 2 elementtype arrayname[]; // C convention elementtype can be any data type. The declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. 7 So, you cannot assign elements to an array unless it has already been created. 7 If a variable does not contain a reference to an array, the value of the variable is null. Zheng-Liang Lu Java Programming 216 / 249
25 Creating An Array 1 elementtype[] myarray = new elementtype[size]; All arrays of Java are objects. So new operator returns the reference 8 after creating an array object. The assignment operator (=) assigns the reference of the newly created array to the reference variable. The type of reference variable must be compatible to that of the array object. The positive integer size is the number of elements for the array object. Note that the size of an array cannot be changed after the array is created. 9 8 Aka the memory address. 9 You can try the ArrayList class. See any textbook for Data Structures. Zheng-Liang Lu Java Programming 217 / 249
26 Arrays in Memory For example, 1 int[] myarray = new int[3]; The elements are integers in this example. All elements of an array are stored contiguously in memory. Arrays in Java are zero-based indexing. (Why?) So we have myarray[0], myarray[1], and myarray[2]. Zheng-Liang Lu Java Programming 218 / 249
27 Array Initializer Arrays can be initialized when they are declared. When an array is created, its elements are assigned the default value: 0 for the numeric primitive data type \u0000 for char type false for boolean type An array can be initialized by enumerating all the elements in a list. For example, 1 int[] myarray = {1, 2, 3}; Note that there is no need to use new. Zheng-Liang Lu Java Programming 219 / 249
28 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. For all array objects, there is a field called length which records the size of this array. For example, use myarray.length to get the size of myarray. Zheng-Liang Lu Java Programming 220 / 249
29 Initializing arrays with input values for (int i = 0; i < myarray.length; ++i) { 3 myarray[i] = in.nextint(); 4 } 5... Initializing arrays with random values for (int i = 0; i < myarray.length; ++i) { 3 myarray[i] = Math.random() 100; 4 } 5... Zheng-Liang Lu Java Programming 221 / 249
30 Displaying arrays for (int i = 0; i < myarray.length; ++i) { 3 System.out.println(myArray[i] + " "); 4 } 5... Summing all elements double sum = 0; 3 for (int i = 0; i < myarray.length; ++i) { 4 sum += myarray[i]; 5 } 6... Zheng-Liang Lu Java Programming 222 / 249
31 Finding the extreme values double max = myarray[0]; 3 double min = myarray[0]; 4 for (int i = 1; i < myarray.length; ++i) { 5 if (max < myarray[i]) max = myarray[i]; 6 if (min > myarray[i]) min = myarray[i]; 7 } 8... Zheng-Liang Lu Java Programming 223 / 249
32 Finding the small index of the extreme elements double max = myarray[0]; 3 double min = myarray[0]; 4 int ind max = 0, ind min = 0; 5 for (int i = 1; i < myarray.length; ++i) { 6 if (max < myarray[i]) { 7 max = myarray[i]; 8 ind max = i; 9 } 10 if (min > myarray[i]) { 11 min = myarray[i]; 12 ind min = i; 13 } 14 } Zheng-Liang Lu Java Programming 224 / 249
33 Random shuffling for (int i = 0; i < myarray.length; ++i) { 3 int j = (int) (Math.random() myarray.length); 4 // swap 5 double tmp = myarray[i]; 6 myarray[i] = myarray[j]; 7 myarray[j] = tmp; 8 } 9... Shifting elements toward left double tmp = myarray[0]; 3 for (int i = 1; i < myarray.length; ++i) { 4 myarray[i 1] = myarray[i]; 5 } 6 myarray[myarray.length 1] = tmp; 7... Zheng-Liang Lu Java Programming 225 / 249
34 Copying Arrays To copy the contents of one array into another, you have to copy the array s individual elements into the other array. In practice, we often need to duplicate an array to another. One could attempt to use the assignment statement (=). For example, newarray = oldarray; 3... It is impossible make two distinct arrays. Zheng-Liang Lu Java Programming 226 / 249
35 Recall that arrays are objects. Reference variables contain only the memory addresses. So you just copy the memory address to another reference variable!!! For another example, Zheng-Liang Lu Java Programming 227 / 249
36 Use a loop to copy individual elements one by one int[] srcarray = {2, 1, 3, 5, 10}; 3 int[] dstarray = new int[srcarray.length]; 4 for (int i = 0; i < srcarray.length; ++i) { 5 dstarray[i] = srcarray[i]; 6 } 7... Use the static arraycopy method in the System class int[] srcarray = {2, 1, 3, 5, 10}; 3 int[] dstarray = new int[srcarray.length]; 4 System.arraycopy(srcArray, 0, dstarray, 0, srcarray.length); 5... Zheng-Liang Lu Java Programming 228 / 249
37 for-each Loops 10 A for-each loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish for (type itervar: myarray) { 3 statments; 4 } 5... Note that itervar should match the element type of myarray. 10 Beginning with JDK5. Now we have JDK8. Zheng-Liang Lu Java Programming 229 / 249
38 Example int[] nums = {1, 2, 3, 4, 5, 6, 7, 8,9, 10}; 3 int sum = 0; 4 for (int i = 0; i < nums.length; ++i) 5 sum += nums[i]; 6... Not only is the syntax streamlined, but it also prevents boundary errors int[] nums = {1, 2, 3, 4, 5, 6, 7, 8,9, 10}; 3 int sum = 0; 4 for (int x: nums) 5 sum += x; 6... Zheng-Liang Lu Java Programming 230 / 249
39 Exercise Deck of Cards Write a program which picks first four cards at random from a deck of 52 cards. 4 suits: Spades, Hearts, Diamonds, Clubs 13 ranks: 2,..., 10, J, Q, K, A Labeling 52 cards by 0, 1,, 51 by a certain rule Shuffle the numbers Pick up the first 4 cards Zheng-Liang Lu Java Programming 231 / 249
40 int[] deck = new int[52]; // defaults are zeros 3 String[] suits = {"Spade", "Heart", "Diamond", "Club"}; 4 String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; 5 6 for (int i = 0; i < deck.length; ++i) deck[i] = i; 7 8 for (int i = 0; i < deck.length; ++i) { 9 int j = (int) (Math.random() deck.length); 10 int tmp = deck[i]; 11 deck[i] = deck[j]; 12 deck[j] = tmp; 13 } for (int i = 0; i < 4; ++i) { 16 String suit = suits[deck[i] / 13]; 17 String rank = ranks[deck[i] % 13]; 18 System.out.printf("Card number %3d : %s of % 8s\n", deck[i], rank, suit); 19 } Zheng-Liang Lu Java Programming 232 / 249
41 Passing Arrays to Methods When passing an array to a method, the reference of the array is passed to the method public static void main(string[] arges) { 3 int[] deck = new int[52]; // defaults are zeros 4 String[] suits = {"Spade", "Heart", "Diamond", "Club"}; 5 String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; 6 7 init(deck); 8 randomshuffle(deck); 9 show(deck); 10 } Zheng-Liang Lu Java Programming 233 / 249
42 static void init(int[] x) { 3 for (int i = 0; i < x.length; ++i) 4 x[i] = i; 5 } 6 7 static void randomshuffle(int[] x) { 8 for (int i = 0; i < x.length; ++i) { 9 int pos = (int) (Math.random() x.length); 10 int tmp = x[i]; 11 x[i] = x[pos]; 12 x[pos] = tmp; 13 } 14 } static void show(int[] x) { 17 for (int i = 0; i < 4; ++i) { 18 String suit = suits[x[i] / 13]; 19 String rank = ranks[x[i] % 13]; 20 System.out.printf("Card number %3d : %s of % 8s\n", x[i], rank, suit); 21 } 22 } Zheng-Liang Lu Java Programming 234 / 249
43 Returning an Array from a Method When a method returns an array, the reference of the array is returned. Reversing an array Write a program which reverses the elements of the array and redirects the resulting array to a new array public static void main(string[] args) { 3 int[] myarray = new int[5]; 4 for (int i = 0; i < myarray.length; ++i) 5 myarray[i] = (int) (Math.random() 10); 6 show(myarray); 7 int[] reversearray = reverse(myarray); 8 show(reversearray); 9 } Zheng-Liang Lu Java Programming 235 / 249
44 static int[] reverse(int[] srcarray) { 3 int[] dstarray = new int[srcarray.length]; 4 for (int i = 0; i < srcarray.length; ++i) { 5 dstarray[srcarray.length 1 i] = srcarray[i]; 6 } 7 return dstarray; 8 } 9 10 static void show(int[] x) { 11 for (int i = 0; i < x.length; ++i) { 12 System.out.printf("x[%d] = %d\n", i, x[i]); 13 } 14 } Zheng-Liang Lu Java Programming 236 / 249
45 Arrays Class The java.util.arrays class contains useful methods for common array operations such as sorting and searching int[] myarray = new int[10]; 3 for (int i = 0; i < myarray.length; ++i) 4 myarray[i] = (int) (Math.random() 10); 5 java.util.arrays.sort(myarray); // sort the whole array 6 7 char[] mychars = new char[10]; 8 for (int i = 0; i < mychars.length; ++i) 9 mychars[i] = (char) (Math.random() ( z a ) + a ); 10 java.util.arrays.sort(mychars, 1, 3); // sort the whole array Zheng-Liang Lu Java Programming 237 / 249
46 Exercise Write a program which searches for the index if the input is a valid key element. How to do a search? The linear search approach compares the key element key sequentially with each element in the array. Zheng-Liang Lu Java Programming 238 / 249
47 public static void main (String[] args) { 3 Scanner in = new Scanner(System.in); 4 int[] myarray = randomarray(5); 5 int index; 6 show(myarray); 7 8 System.out.println("Enter a key number? "); 9 int key = in.nextint(); 10 in.close(); index = searchkey(myarray, key); if (index > 1) 15 System.out.printf("Key element %d is at index %d.\n", key, index); 16 else 17 System.out.printf("Key element %d does not exist.\n", key); 18 } static int searchkey(int[] targetarray, int inquiry) { 21 int index = 1; 22 for (int i = 0; i < targetarray.length; ++i) { Zheng-Liang Lu Java Programming 239 / 249
48 23 if (inquiry == targetarray[i]) 24 index = i; 25 } 26 return index; 27 } static int[] randomarray(int n) { 30 int[] x = new int[n]; 31 for (int i = 0; i < n; ++i) 32 x[i] = (int) (Math.random() 100); 33 return x; 34 } static void show(int[] x) { 37 for (int i = 0; i < x.length; ++i) 38 System.out.printf("[%2d] = % 3d\n", i, x[i]); 39 System.out.println(); 40 } Time complexity: O(n) Zheng-Liang Lu Java Programming 240 / 249
49 Binary Search Time complexity: O(log n) Overall time complexity (sorting + searching): still O(log n)? Zheng-Liang Lu Java Programming 241 / 249
50 static int searchkey(int[] x, int y) { // binary search 3 System.out.println("Binary search..."); 4 int low = 0; 5 int high = x.length 1; 6 int mid = 1; 7 System.out.println("Sorting..."); 8 java.util.arrays.sort(x); 9 show(x); while (high >= low) { 12 mid = (high + low) / 2; 13 if (x[mid] > y) 14 high = mid 1; 15 else if (x[mid] == y) 16 return mid; 17 else 18 low = mid + 1; 19 } 20 return mid; 21 } Zheng-Liang Lu Java Programming 242 / 249
51 Variable-Length Argument Lists A variable number of arguments of the same type can be passed to a method and treated as an array. Java treats a variable-length parameter as an array. Zheng-Liang Lu Java Programming 243 / 249
52 Example 1 public class VarArgMain { 2 public static void main (String[] args) { 3 findmax(1,5,3,7,8,2); 4 findmax(2,3,5,9,6); 5 } 6 7 static void findmax(int...x) { 8 int max = x[0]; 9 for (int i: x) { 10 if (max < i) 11 max = i; 12 } 13 System.out.printf("Max = %d\n", max); 14 } 15 } Zheng-Liang Lu Java Programming 244 / 249
53 Two-Dimensional Array An element in a two-dimensional array is accessed through a row and column index. 1 int[][] myarray = new int[rowsize][colsize]; rowsize and colsize specify the sizes for rows and columns, respectively. Zheng-Liang Lu Java Programming 245 / 249
54 Zheng-Liang Lu Java Programming 246 / 249
55 Equivalence Zheng-Liang Lu Java Programming 247 / 249
56 Zheng-Liang Lu Java Programming 248 / 249
57 Problem Set Exercise 6.1 (Matrix Multiplication) Write a program which determines C = A B for any two input matrices A m n, B n k. Zheng-Liang Lu Java Programming 249 / 249
Variable Scope. The variable scope is the range of the program where the variable can be referenced.
Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets
More informationExercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.
Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //
More information1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174
1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationHow to swap values of two variables without tmp? However, this naive algorithm is biased. 1
Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...
More informationMethod Invocation. Zheng-Liang Lu Java Programming 189 / 226
Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters
More information1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207
1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having
More informationThe return Statement
The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return
More informationRecursion 1. Recursion is the process of defining something in terms of itself.
Recursion 1 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition
More information1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248
1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚,
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationJava Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University
Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug., 2016 U Hou Lok Java Programming 1 / 51 A Math Toolbox: Math Class The
More informationModule 7: Arrays (Single Dimensional)
Module 7: Arrays (Single Dimensional) Objectives To describe why arrays are necessary in programming ( 7.1). To declare array reference variables and create arrays ( 7.2.1 7.2.2). To obtain array size
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
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:
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
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:
More informationExample: Fibonacci Numbers
Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers
More information1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244
1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 186 / 244 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea
More informationTwo Approaches to Algorithms An Example (1) Iteration (2) Recursion
2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits
More informationChapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6 Single-Dimensional Arrays rights reserved. 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. Solution AnalyzeNumbers rights
More informationOpening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.
Chapter 6 Arrays 1 Opening Problem EXAMPLE 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average. 2 Introducing Arrays Array is a data structure
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 172 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationLecture #8-10 Arrays
Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationChapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.
Chapter 7: Single-Dimensional Arrays Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average CS1: Java Programming Colorado State University
More informationAnnouncements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am
Announcements PS 4 is ready, due next Thursday, 9:00pm Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both
More informationCS115 Principles of Computer Science
CS5 Principles of Computer Science Chapter Arrays Prof. Joe X. Zhou Department of Computer Science CS5 Arrays. Re: Objectives in Methods To declare methods, invoke methods, and pass arguments to a method
More informationNested Loops. A loop can be nested inside another loop.
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
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationRecursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms
Recursive Methods and Problem Solving Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Review: Calling Methods int x(int n) { int m = 0; n = n + m + 1; return n; int y(int
More informationCS 310 Advanced Data Structures and Algorithms
CS 310 Advanced Data Structures and Algorithms Recursion June 27, 2017 Tong Wang UMass Boston CS 310 June 27, 2017 1 / 20 Recursion Recursion means defining something, such as a function, in terms of itself
More informationObject Oriented Programming. Java-Lecture 6 - Arrays
Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types
More informationChapter 7 Single-Dimensional Arrays
Chapter 7 Single-Dimensional Arrays 1 Arrays Array is a data structure that represents a collection of same-types data elements. A single-dimensional array is one that stores data elements in one row.
More informationInf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics
Inf1-OP Arrays 1 Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics January 30, 2017 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays:
More informationInf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin
Inf1-OOP Arrays 1 Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin January
More informationInf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics
Inf1-OOP Arrays 1 Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics January 11, 2015 1 Thanks to Sedgewick&Wayne for much of this content Arrays Introduction to Arrays Arrays
More informationPearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world
Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsoned.co.uk Pearson Education Limited 2014
More informationWentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion
Lecture 13 1 What is? A method of programming in which a method refers to itself in order to solve a problem Never necessary In some situations, results in simpler and/or easier-to-write code Can often
More informationChapter 6 Recursion. The Concept of Recursion
Data Structures for Java William H. Ford William R. Topp Chapter 6 Recursion Bret Ford 2005, Prentice Hall The Concept of Recursion An algorithm is recursive if it can be broken into smaller problems of
More informationInf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics
Inf1-OP Arrays 1 Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays Arrays:
More informationArrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein
Inf1-OP Arrays 1 Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein Arrays School of Informatics February 26, 2018 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays:
More informationArrays. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays
More information1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.
A Foundation for Programming 1.4 Arrays any program you might want to write objects functions and modules graphics, sound, and image I/O arrays store and manipulate huge quantities of data conditionals
More informationCS1150 Principles of Computer Science Arrays
CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their
More informationArrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)
Arrays Chapter 7 (Done right after 4 arrays and loops go together, especially for loops) Object Quick Primer A large subset of Java s features are for OOP Object- Oriented Programming We ll get to that
More informationRecursion. Chapter 5
Recursion Chapter 5 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn
More information! 52 playing cards in a deck. ! 5 thousand undergrads at Princeton. ! 1 million characters in a book. ! 10 million audio samples in an MP3 file.
Arrays 1.4 Arrays This lecture. Store and manipulate huge quantities of data. Array. Indexed sequence of values of the same type. Examples.! 52 playing cards in a deck.! 5 thousand undergrads at Princeton.!
More informationJava is an objet-oriented programming language providing features that support
Java Essentials CSCI 136: Spring 2018 Handout 2 February 2 Language Basics Java is an objet-oriented programming language providing features that support Data abstraction Code reuse Modular development
More informationChapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 6 Methods Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from
More informationq To develop recursive methods for recursive mathematical functions ( ).
Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There
More informationq To develop recursive methods for recursive mathematical functions ( ).
/2/8 Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem?
More informationLiang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
1 To describe why arrays are necessary in programming ( 6.1). To declare array reference variables and create arrays ( 6.2.1-6.2.2). To initialize the values in an array ( 6.2.3). To access array elements
More informationArrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 06: Arrays Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1 Instructor AbuKhleif, Mohammad Noor Computer Engineer
More informationArrays and Lists CSC 121 Fall 2014 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #9: Arrays Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More information8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?
8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive
More informationC22a: Problem Solving using Recursion
CISC 3115 TY3 C22a: Problem Solving using Recursion Hui Chen Department of Computer & Information Science CUNY Brooklyn College 11/6/2018 CUNY Brooklyn College 1 Outline Characteristics of recursion Recursion
More information34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
34. Recursion Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Example: Factorials Example: Fibonacci Numbers Recursion vs. Iteration References Introduction Introduction Recursion
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More information1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write
A Foundation for Programming 1.4 Arrays any program you might want to write objects functions and modules graphics, sound, and image I/O arrays store and manipulate huge quantities of data conditionals
More informationChapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 6 Arrays 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 2 Solution AnalyzeNumbers Run Run with prepared input 3 Objectives
More informationData Structures And Algorithms
Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:
More informationDebugging [continued]
1 Debugging [continued] Admiral Grace Murray Hopper http://www.history.navy.mil/photos/images/h96000/h96566kc.htm 2 Debugging Your Program Debugging Your Program. [summary] 1. Edit the program (type in
More informationData dependent execution order data dependent control flow
Chapter 5 Data dependent execution order data dependent control flow The method of an object processes data using statements, e.g., for assignment of values to variables and for in- and output. The execution
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationCMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park
CMSC 132: Object-Oriented Programming II Recursive Algorithms Department of Computer Science University of Maryland, College Park Recursion Recursion is a strategy for solving problems A procedure that
More informationCS1150 Principles of Computer Science Arrays
CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their
More information11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1
RECURSION Chapter 5 Recursive Thinking Section 5.1 1 Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that are difficult
More informationLast Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it
Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]
More informationReduction & Recursion Overview
Reduction & Recursion Overview Reduction definition Reduction techniques Recursion definition Recursive thinking (Many) recursion examples Indirect recursion Runtime stack Factorial isnumericstring add
More informationValues in 2 s Complement
Values in 2 s Complement Java uses an encoding known as 2 s complement 1, which means that negative numbers are represented by inverting 2 all of the bits in a value, then adding 1 to the result. For example,
More informationRecursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved
Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More informationArrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington
Arrays and Array Lists CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington 1 Motivation Current limitation: We cannot record multiple
More informationExercise (Revisited)
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?"); 4 price = input.nextint(); 5 if (price
More informationArrays and Lists CSC 121 Fall 2016 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationRecursion. Chapter 7
Recursion Chapter 7 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn
More informationLecture 5: Methods CS2301
Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int
More informationRecursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011
Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming
More informationChapter 15: Recursion
Chapter 15: Recursion Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 15 discusses the following main topics: Introduction to Recursion
More informationAryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9
Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths
More informationArrays and Lists CSC 121 Fall 2015 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationChapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University
Opening Problem Chapter 6: Methods Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively CS1: Java Programming Colorado State University Original slides by Daniel Liang
More informationCS/CE 2336 Computer Science II
S/E 2336 omputer Science II UT D Session 10 Recursion dapted from D Liang s Introduction to Java Programming, 8 th Ed 2 factorial(0) = 1; omputing Factorial factorial(n) = n*factorial(n-1); n! = n * (n-1)!
More informationRecursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...
Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial
More informationCONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays
CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202
More informationChapter 18 Recursion. Motivations
Chapter 18 Recursion CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox 1 Motivations Suppose you want to find all the files under a directory
More informationCIS 110 Introduction to Computer Programming Spring 2016 Midterm
CIS 110 Introduction to Computer Programming Spring 2016 Midterm Name: Recitation # (e.g., 201): Pennkey (e.g., eeaton): My signature below certifies that I have complied with the University of Pennsylvania
More informationrecursive algorithms 1
COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative)! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k
More informationEE 368. Weeks 4 (Notes)
EE 368 Weeks 4 (Notes) 1 Read Chapter 3 Recursion and Backtracking Recursion - Recursive Definition - Some Examples - Pros and Cons A Class of Recursive Algorithms (steps or mechanics about performing
More informationArrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003
Arrays COMS W1007 Introduction to Computer Science Christopher Conway 10 June 2003 Arrays An array is a list of values. In Java, the components of an array can be of any type, basic or object. An array
More informationRecursion. Fundamentals of Computer Science
Recursion Fundamentals of Computer Science Outline Recursion A method calling itself All good recursion must come to an end A powerful tool in computer science Allows writing elegant and easy to understand
More informationNews and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!
True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,
More informationChapter 6 SINGLE-DIMENSIONAL ARRAYS
Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More information