Variable Scope. The variable scope is the range of the program where the variable can be referenced.
|
|
- Abel Tucker
- 6 years ago
- Views:
Transcription
1 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 defines a particular scope. Moreover, one can declare variables with the same name in different levels of scopes. Yet, one cannot declare the variables with the same name in the same scope. Zheng-Liang Lu Java Programming 186 / 232
2 Example 1 public class incrementmain { 2 3 static int i = 1; // Aka class member. 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", i); // Where is i? 7 int i = 2; 8 i++; 9 System.out.printf("%d\n", i); 10 p(); 11 System.out.printf("%d\n", i); 12 } static void p() { 15 i = i + 1; 16 System.out.printf("%d\n", i); 17 } 18 } Zheng-Liang Lu Java Programming 187 / 232
3 Overloading Methods Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloading methods can make programs clearer and more readable. Note that overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Zheng-Liang Lu Java Programming 188 / 232
4 Exercise (Revisit) Star printing Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats its procedure until the number of lines is negative. If the user enter -1, use * as the default symbol. Zheng-Liang Lu Java Programming 189 / 232
5 static void print(int x, String marker) { 3 for (int i = 1; i <= x; ++i){ 4 for (int j = 1; j <= i; ++j) 5 System.out.printf("%s", marker); 6 System.out.println(); 7 } 8 } 9 10 static void print(int x) { 11 for (int i = 1; i <= x; ++i){ 12 for (int j = 1; j <= i; ++j) 13 System.out.printf(" "); 14 System.out.println(); 15 } 16 } print()s are overloaded. Zheng-Liang Lu Java Programming 190 / 232
6 public static void main (String[] args) { while (true) { 5 System.out.println("Enter a positive integer? "); 6 n = in.nextint(); 7 if (n < 0) break; 8 System.out.println("Choose a symbol? ( 1 to use the default symbol )"); 9 marker = in.next(); 10 if (marker.equals(" 1")) 11 print(n); 12 else 13 print(n, marker); 14 } } in.next() returns a string from keyboard. Be aware that in.next() skips the blanks in the beginning of line. marker.equals() is one method of String object. Zheng-Liang Lu Java Programming 191 / 232
7 Math Class The Math class contains the methods needed to perform basic mathematical functions. The Math class is public. All methods of Math class are public and static with two global constants Math.PI 1 and Math.E 2. The Math class provides common methods like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document of Math class can be found here. 1 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as e is the base of the natural logarithm. It is approximately equal to Zheng-Liang Lu Java Programming 192 / 232
8 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 / 232
9 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A + 1) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a + 1) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( ) + 0 ); 12 } Zheng-Liang Lu Java Programming 194 / 232
10 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 / 232
11 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 / 232
12 Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 197 / 232
13 Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 198 / 232
14 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 so-called encapsulation. Zheng-Liang Lu Java Programming 199 / 232
15 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 / 232
16 Recursion 3 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. 3 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 201 / 232
17 Try Fractal. Zheng-Liang Lu Java Programming 202 / 232
18 In general, to solve a problem using recursion, you break it into subproblems. Each subproblem is the same as the original problem but smaller in size. You can apply the same approach to each subproblem to solve it recursively. Zheng-Liang Lu Java Programming 203 / 232
19 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. 4 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? 4 Note that 0! = 1. Zheng-Liang Lu Java Programming 204 / 232
20 Zheng-Liang Lu Java Programming 205 / 232
21 Write a program which determines the 10th factorials static int factorial(int n) { 3 if (n!= 0) 4 return n factorial(n 1); 5 else 6 return 1; // base condition 7 } 8... 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 206 / 232
22 Equivalence: Recursion Replaced by Loops int x = 1; 3 for (int i = 10; i > 0; i = i 1) 4 x = i; 5... One intriguing question is, Can we always turn a recursive method into an iterative one? Yes, theoretically. 5 5 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 207 / 232
23 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. 6 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. 6 Stack overflow. Zheng-Liang Lu Java Programming 208 / 232
24 Zheng-Liang Lu Java Programming 209 / 232
25 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 210 / 232
26 The recursive implementation of fib is very simple and straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. 7 7 fib is an exponential-time algorithm while factorial is a linear-time algorithm. (Why?) Zheng-Liang Lu Java Programming 211 / 232
27 static int fib(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 } public static void main(string[] args) { 3 int x = 0, y = 1; 4 int tmp = 0; 5 for (int i = 0; i < 10; ++i){ 6 if (i == 0 i == 1) 7 System.out.printf("%2d: %7d\n", i, ((i == 1)? y : x)); 8 else { 9 tmp = x + y; 10 x = y; 11 y = tmp; 12 System.out.printf("%2d: %7d\n", i, y); 13 } 14 } 15 } Zheng-Liang Lu Java Programming 212 / 232
28 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 / 232
29 Zheng-Liang Lu Java Programming 214 / 232
30 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 / 232
31 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. 8 So, you cannot assign elements to an array unless it has already been created. 8 If a variable does not contain a reference to an array, the value of the variable is null. Zheng-Liang Lu Java Programming 216 / 232
32 1 myarray = new elementtype[size]; Creating An Array All arrays in Java are objects. So, new operator returns the reference after creating an object of array. Note that the reference variable type must match the type of object reference returned by the new operator. size is the number of elements in myarray. The assignment operator (=) assigns the reference of the newly created array 9 to myarray. Note that the size of an array cannot be changed after the array is created Aka the memory address. 10 You can try the ArrayList class. Zheng-Liang Lu Java Programming 217 / 232
33 Arrays in Memory 1 int[] myarray = new int[3]; All elements of an array are stored contiguously in memory. Arrays in Java are zero-based indexing. (Why?) So, myarray[0], myarray[1], and myarray[2]. Zheng-Liang Lu Java Programming 218 / 232
34 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 types \u0000 for char types false for boolean types An array initializer is a list of comma-separated expressions surrounded by curly braces int[] myarray = {value0, value1, value2,..., valuek}; 3... Note that there is no need to use new. Zheng-Liang Lu Java Programming 219 / 232
35 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. myarray.length returns the number of elements in myarray. Zheng-Liang Lu Java Programming 220 / 232
36 Initializing arrays with input values for (int i = 0; i < myarray.length; ++i) 3 myarray[i] = in.nextdouble(); 4... Initializing arrays with random values for (int i = 0; i < myarray.length; ++i) 3 myarray[i] = Math.random() 100; 4... Zheng-Liang Lu Java Programming 221 / 232
37 Displaying arrays for (int i = 0; i < myarray.length; ++i) 3 System.out.println(myArray[i] + " "); 4... Summing all elements double sum = 0; 3 for (int i = 0; i < myarray.length; ++i) 4 sum += myarray[i]; 5... Zheng-Liang Lu Java Programming 222 / 232
38 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 / 232
39 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 / 232
40 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 myarray[myarray.length 1] = tmp; 6... Zheng-Liang Lu Java Programming 225 / 232
41 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 (=) as follows: // myarray new and myarray old are arrays. 3 myarary new = myarray old; 4... Zheng-Liang Lu Java Programming 226 / 232
42 It is impossible make two distinct arrays. Recall that arrays in Java are objects. Array variables contain only the memory addresses. In Line 3, myarray new refers to the same array as myarray old! For another example, Zheng-Liang Lu Java Programming 227 / 232
43 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... 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 / 232
44 for-each Loops 11 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. 11 Beginning with JDK5. Now we have JDK8. Zheng-Liang Lu Java Programming 229 / 232
45 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... But it is not almighty! Zheng-Liang Lu Java Programming 230 / 232
46 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 / 232
47 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 / 232
Example. Password generator
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
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 "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 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 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 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 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" // 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 information1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.
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 41 / 68 Example Given the radius
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
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 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 informationINTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from
INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function
More informationMethods (Deitel chapter 6)
Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
More informationMethods (Deitel chapter 6)
1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
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 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 informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More informationLecture #6-7 Methods
Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
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 informationCS115 Principles of Computer Science
CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops)
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 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 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 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 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 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 informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationLecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson
Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=
More informationCOMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
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 informationIntroduction to Software Development (ISD) Week 3
Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process
More informationFall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals
INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer
More informationObject-Based Programming. Programming with Objects
ITEC1620 Object-Based Programming g Lecture 8 Programming with Objects Review Sequence, Branching, Looping Primitive datatypes Mathematical operations Four-function calculator Scientific calculator Don
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
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 informationChapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }
Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,
More informationData Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87
Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and
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 informationLecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.
Lecture 05: Methods AITI Nigeria Summer 2012 University of Lagos. Agenda What a method is Why we use methods How to declare a method The four parts of a method How to use (invoke) a method The purpose
More informationQ1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question
Page 1 of 6 Template no.: A Course Name: Computer Programming1 Course ID: Exam Duration: 2 Hours Exam Time: Exam Date: Final Exam 1'st Semester Student no. in the list: Exam pages: Student's Name: Student
More informationIntroduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur
Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture - 23 Introduction to Arduino- II Hi. Now, we will continue
More informationMethods: A Deeper Look
1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number
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 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 informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationGlobal Variables. ˆ Unlike local variables, global variables are available to all functions involved.
Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is
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 information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples
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 informationCS110: PROGRAMMING LANGUAGE I
CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters
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 informationMethods and Functions
Programming with Java Module 4 Methods and Functions Theoretical Part Contents 1 Module overview 3 2 Methods 3 2.1 Methods without return value (procedures).............. 3 2.2 Functions with return value
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 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 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 informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
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 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 informationFunctions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
More informationCS1150 Principles of Computer Science Loops (Part II)
CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and
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 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 information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More informationActivity 4: Methods. Content Learning Objectives. Process Skill Goals
Activity 4: Methods Java programs are organized into classes, each of which has one or more methods, each of which has one or more statements. Writing methods allows you to break down a complex program
More informationSimple Java Reference
Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...
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 information1001ICT Introduction To Programming Lecture Notes
1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming
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 informationOVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?
CH. 5 RECURSION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OVERVIEW Recursion is an algorithmic
More information4. Java language basics: Function. Minhaeng Lee
4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only
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 informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More information