1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Size: px
Start display at page:

Download "1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207"

Transcription

1 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

2 Loops A loop can be used to make a program execute statements repeatedly without having to code the same statements. For example, a program prints Hello, Java. for 100 times. 1 System.out.println("Hello, Java."); 2 System.out.println("Hello, Java."); // Copy and paste for 100 times 5. 6 System.out.println("Hello, Java."); Zheng-Liang Lu Java Programming 126 / 207

3 1 int cnt = 0; 2 while (cnt < 100) { 3 System.out.println("Hello, Java."); 4 cnt++; 5 } This is a simple example to show the power of loops. In practice, any routine which repeats couples of times 1 can be done by folding them into a loop. 1 I d like to call them patterns. Zheng-Liang Lu Java Programming 127 / 207

4 Flow Controls (Recap) The concept of looping, which is one of elements in algorithms, is fundamental to programming. Loops provide significant computation power. Loops bring an efficient way of programming. Loops could consume a lot of time. 2 2 We will visit the analysis of algorithm. Zheng-Liang Lu Java Programming 128 / 207

5 while Loops A while loop executes statements repeatedly while the condition is true. 1 while (loop continuation condition) { 2 statements; // loop body 3 } The loop-continuation-condition is a Boolean expression which controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If true, the loop body is executed. Otherwise, the entire loop terminates. Zheng-Liang Lu Java Programming 129 / 207

6 Zheng-Liang Lu Java Programming 130 / 207

7 Example Write a program which sums up all integers from 1 to 100. You can choose to write a program like this: 1 int sum=0; 2 sum=sum+1; 3 sum=sum+2; sum=sum+100; Pros: Not efficient, not general (what if sum up to 10 10?) Zheng-Liang Lu Java Programming 131 / 207

8 Using a while loop, the program looks like this: int sum = 0; 3 int i = 0; 4 while (++i <= 100) 5 sum = sum + i; 6... Make sure that the loop-continuation-condition eventually becomes false so that the loop will terminate. It is really easy to make an infinite loop while(true); 3... Zheng-Liang Lu Java Programming 132 / 207

9 Besides, replacing 100 by n determined by the user makes this program more general Scanner input = new Scanner(System.in); 3 int n = input.nextint(); 4 int sum = 0; 5 int i = 0; 6 while (++i <= n) 7 sum = sum + i; 8... In practice, the number of loop steps is unknown until the input data is given. For example, the bisection algorithm provides a numerical solution to root-finding problems. Zheng-Liang Lu Java Programming 133 / 207

10 Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct public static void main (String[] args) { 3 // random integer generation 4 int number1 = (int)(math.random() % 10); 5 int number2 = (int)(math.random() % 10); 6 7 Scanner input = new Scanner(Sysmte.in); 8 System.out.println(number1 + " + " + number2 + " =?"); 9 int ans = input.nextint(); while (number1 + number2!= ans) { 12 System.out.println("Wrong answer. Try again?"); 13 ans = input.nextint(); 14 } 15 System.out.println("Congrats! You are smart!"); 16 } Zheng-Liang Lu Java Programming 134 / 207

11 Loop Design Strategies Writing a correct loop is not an easy task for novice programmers. Consider 4 steps when writing a loop: Identify the statements that need to be repeated. Wrap these statements in a loop. Find an appropriate loop continuation condition 3. Add, if necessary, extra statements for controlling the loop 4. 3 Not unique. 4 Make sure that the condition can turn to false. Zheng-Liang Lu Java Programming 135 / 207

12 Sentinel-Controlled Loop Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. Zheng-Liang Lu Java Programming 136 / 207

13 Example Write a program which sums real numbers from the input except for -1 to exit, and displays the sum Scanner in = new Scanner(System.in); 3 double sum = 0; 4 System.out.println("Please enter a real number ( 1 to exit): "); 5 double x = in.nextdouble(); 6 while(x!= 1) { 7 sum += x; 8 System.out.println("Please enter a real number ( 1 to exit): "); 9 x = in.nextdouble(); 10 } 11 System.out.println("Sum = " + sum); 12 in.close(); Try more features? Zheng-Liang Lu Java Programming 137 / 207

14 do-while Loops A do-while loop is the same as a while loop except that it does execute the loop body first and then checks the loop continuation condition do { 3 statements; 4 } while (loop continuation condition); 5 // Do not miss the semicolon! 6... Note that there is a semicolon at the end the do-while loop. do-while loops are also called posttest loop, in contrast to while loops, which are pretest loops. Zheng-Liang Lu Java Programming 138 / 207

15 Zheng-Liang Lu Java Programming 139 / 207

16 Example Write a program which allows the user to enter positive integers except for -1 to exit, and displays the maximum. Zheng-Liang Lu Java Programming 140 / 207

17 Scanner in = new Scanner(System.in); 3 int max = 0, x; 4 do{ 5 System.out.println("Please enter a positive integer ( 1 to exit): "); 6 x = in.nextint(); 7 if(max < x) { 8 max = x; 9 } 10 System.out.println("Max = " + max); 11 } while(x!= 1); 12 in.close(); Zheng-Liang Lu Java Programming 141 / 207

18 for Loops A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates for(init; condition; increment) { 3 statements; // loop body 4 } 5... init: initialize a variable condition: a criteria that a loop continues increment: how the variable changes after each iteration Note that the three terms are separated by a semicolon. Zheng-Liang Lu Java Programming 142 / 207

19 Example Sum from 1 to 100 Write a program which sums from 1 to int sum = 0; 3 for (int i = 1; i <= 100; ++i) 4 sum = sum + i; 5... Compared to the while version, int sum = 0; 3 int i = 0; 4 while (++i <= 100) 5 sum = sum + i; 6... Zheng-Liang Lu Java Programming 143 / 207

20 Zheng-Liang Lu Java Programming 144 / 207

21 Example: Selection Resided in Loop Display all even numbers Write a program which displays all even numbers smaller than 100. An even number is an integer of the form x = 2k, where k is an integer. You may use modular operator (%) for (int i = 1; i <= 100; i++) { 3 if (i % 2 == 0) 4 System.out.println(i); 5 } 6... How about odd numbers? Zheng-Liang Lu Java Programming 145 / 207

22 for Loops: Multiple Loop Variables The init in a for loop can be a list of zero or more commaseparated variable declaration statements or assignment expressions for (int i = 0, j = 0; (i + j < 10); i++, j+=2) { 3 System.out.println("(i,j) = " + "(" + i + ", " + j + ")" ); 4 } 5... The last line on display is? Zheng-Liang Lu Java Programming 146 / 207

23 Jump Statements Two keywords, break and continue, can be used in loop statements to provide additional controls. break: The loop is terminated right after a break statement is executed. continue: The loop skips this iteration right after a continue statement is executed. Normally, jump statements are used within selection structures in loops. Zheng-Liang Lu Java Programming 147 / 207

24 Example Check if the input number is a prime) Write a program which determine if the input integer is a prime. Recall that a prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Let x be any natural number. The most naive approach is to divide x by all natural numbers smaller than x. A better approach is to to divide x by all natural numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 148 / 207

25 Scanner in = new Scanner(System.in); 3 System.out.println("Please enter an integer: "); 4 int x = in.nextint(); 5 in.close(); 6 for (int i = 2; i <= (int) Math.sqrt(x); i++) { 7 if ((x % i) == 0) { 8 System.out.println(x + " is not a prime."); 9 break; 10 } 11 if (i == (int) Math.sqrt(x)) 12 System.out.println(x + " is a prime."); 13 } Zheng-Liang Lu Java Programming 149 / 207

26 Equivalence: while and for Loops Compounding problem Write a program which determines the number of years n if the initial amount of saving is 10, 000 NTD, then the compounding amount of saving exceeds 15, 000 NTD. Zheng-Liang Lu Java Programming 150 / 207

27 1 import java.util.scanner; 2 3 public class compoudingmain { 4 public static void main(string[] args) { 5 Scanner in = new Scanner(System.in); 6 System.out.println("r =?"); 7 double r = in.nextdouble(); 8 System.out.println("x =?"); 9 double x = in.nextdouble(); 10 System.out.println("y =?"); 11 double y = in.nextdouble(); 12 int n = 0; 13 while (x = (1 + r)) <= y) 14 n = n + 1; 15 System.out.println("n = " + n); 16 System.out.println("x = " + x); 17 in.close(); 18 } 19 } Note that the listing is a generalized version. Try to extend your work as general as possible. It could be hard, but worth. Zheng-Liang Lu Java Programming 151 / 207

28 int n; 3 for (n = 1; true; n++) { 4 x = (1 + r); 5 if (x >= y) 6 break; 7 } 8... A for loop can be an infinite loop by setting true or simply leaving empty in the condition in for. An infinite for loop with a break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 152 / 207

29 Equivalence: while and for Loops (Concluded) You can use a for loop, a while loop, or a do-while loop, whichever is convenient. In general, a for loop may be used if the number of repetitions is known in advance. If not, then a while loop is preferred. Zheng-Liang Lu Java Programming 153 / 207

30 Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. Zheng-Liang Lu Java Programming 154 / 207

31 Example Multiplication table Write a program which displays a multiplication table. Zheng-Liang Lu Java Programming 155 / 207

32 for (int j = 0; j <= 10; ++j) { 3 if (j == 0) 4 System.out.printf(" "); 5 else if (j!= 10) 6 System.out.printf("%3d", j); 7 else { 8 System.out.printf("\n"); 9 for (int k = 0; k <= j; ++k){ 10 System.out.printf(" "); 11 if (k == j) 12 System.out.printf("\n"); 13 } 14 } 15 } 16 for (int i = 1; i < 10; ++i){ 17 System.out.printf("%3d ", i); 18 for (int j = 1; j < 10; ++j) { 19 System.out.printf("%3d", i j); 20 if (j==9) 21 System.out.printf("\n"); 22 } 23 } Zheng-Liang Lu Java Programming 156 / 207

33 Exercise Zheng-Liang Lu Java Programming 157 / 207

34 1 // Case (a) 2 public class printstars { 3 public static void main(string[] args){ 4 for(int i = 1; i <= 5; i++) { 5 for(int j = 1; j <= i; j++){ 6 System.out.printf(" "); 7 if (j == i) 8 System.out.printf("\n"); 9 } 10 } 11 } 12 } Try on your own for (b), (c), and (d). Allow the user to decide the number of lines? Zheng-Liang Lu Java Programming 158 / 207

35 Problem Set Exercise 4.1 (Greatest common divisor) Write a program which receives two positive integers and returns the greatest common divisor which is the largest positive integer that divides the numbers without a remainder. Exercise 4.2 (Find all prime numbers smaller than 1000) Write a program which displays all prime numbers smaller than Exercise 4.3 (π estimated by Monte Carlo) Write a program which estimates π by Monte Carlo Simulation. Zheng-Liang Lu Java Programming 159 / 207

36 Exercise 4.4 (Find the two highest scores) Write a program that prompts the user to enter the number of students and each student s name and score, and finally displays the student with the highest score and the student with the second-highest score. Exercise 4.5 (Find numbers divisible by 5 and 6) Write a program that displays all the numbers from 100 to 1,000, ten per line, that are divisible by 5 and 6. Numbers are separated by exactly one space. Zheng-Liang Lu Java Programming 160 / 207

37 Exercise 4.6 (Continued from 4.6) Write a program that displays all the numbers from 100 to 200, ten per line, that are divisible by 5 or 6, but not both. Numbers are separated by exactly one space. Exercise 4.7 Write a program that finds the smallest n such that n 2 > using a while loop. Exercise 4.8 Write a program which finds the largest n such that n 3 > using a while loop. Zheng-Liang Lu Java Programming 161 / 207

38 Exercise 4.9 (Display pyramid) Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the following sample run: Zheng-Liang Lu Java Programming 162 / 207

39 Exercise 4.10 (Display numbers in a pyramid pattern) Write a nested for loop that prints the following output: Zheng-Liang Lu Java Programming 163 / 207

40 Exercise 4.11 (Display four patterns using loops) Use nested loops that display the following patterns in four separate programs: Zheng-Liang Lu Java Programming 164 / 207

41 Exercise 4.12 (Display leap years) Write a program that displays all the leap years, ten per line, in the twenty-first century (from 2001 to 2100), separated by exactly one space. Exercise 4.13 (Compute π) You can approximate by using the following series: π = 4( ( 1)i+1 2i 1 ) Write a program that displays the value for i = 10000, 20000,..., and Zheng-Liang Lu Java Programming 165 / 207

42 Exercise 4.14 (Perfect number) A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6 = The next is 28 = There are four perfect numbers less than 10,000. Write a program to find all these four numbers. Exercise 4.15 (Game: scissor, rock, paper) Exercise 3.17 gives a program that plays the scissor-rockpaper game. Revise the program to let the user continuously play until either the user or the computer wins more than two times. Zheng-Liang Lu Java Programming 166 / 207

43 Exercise 4.16 Histogram for math grades Write a program which allows the user to enter the math grades in order (-1 to exit), and makes a histogram. Zheng-Liang Lu Java Programming 167 / 207

44 1 class Lecture5 { 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 168 / 207

45 Methods 5 Methods can be used to define reusable code, and organize and simplify code. 5 Some programming languages refer to methods as procedures and functions. Zheng-Liang Lu Java Programming 169 / 207

46 1 modifier returntype methodname(list of Parameter) { 2 // method body 3 } So far, the modifier could be static, public, and final. returntype could be primitive data types, referential data types, and void. 6 List of Parameter refers to the list of parameters as input of the method. Parameters are optional; that is, a method doesn t have to contain any parameters. The method name and the parameter list together constitute the method signature. 6 A void method does not return a value. Zheng-Liang Lu Java Programming 170 / 207

47 Example Write a program which allows the user to enter the math grades in order (-1 to exit), and makes a histogram. How to count? Zheng-Liang Lu Java Programming 171 / 207

48 Scanner in = new Scanner(System.in); 3 int a, b, c, d, e, x; 4 a = b = c = d = e = 0; 5 do { 6 System.out.printf("Enter ( 1 to exit): "); 7 x = in.nextint(); 8 if (x >= 90) ++a; 9 else if (x >= 80) ++b; 10 else if (x >= 70) ++c; 11 else if (x >= 60) ++d; 12 else if (x >= 0) ++e; 13 else if (x == 1) System.out.println("End of Input..."); 14 else System.out.println("Invalid input."); 15 } while (x!= 1); 16 in.close(); System.out.printf("Total: %d\n", a + b + c + d + e); System.out.printf("%3d %3d: ", 100, 90); 21 for (int i = 0; i < a ; i++) 22 System.out.printf(" "); 23 System.out.printf("\n"); 24 Zheng-Liang Lu Java Programming 172 / 207

49 25 System.out.printf("%3d %3d: ", 89, 80); 26 for (int i = 1; i <= b; i++) 27 System.out.printf(" "); 28 System.out.printf("\n"); System.out.printf("%3d %3d: ", 79, 70); 31 for (int i = 1; i <= c; i++) 32 System.out.printf(" "); 33 System.out.printf("\n"); System.out.printf("%3d %3d: ", 69, 60); 36 for (int i = 1; i <= d; i++) 37 System.out.printf(" "); 38 System.out.printf("\n"); System.out.printf("%3d %3d: ", 59, 0); 41 for (int i = 1; i <= e; i++) 42 System.out.printf(" "); 43 System.out.printf("\n"); Line repeat the same pattern as Line Zheng-Liang Lu Java Programming 173 / 207

50 Recall that we may use a loop when a bundle of instructions are applied to different data. Organize the print() method which displays the stars given the interval (a, b] and the number of stars cnt static void print(int a, int b, int cnt) { 3 System.out.printf("%3d %3d: ", b, a); 4 for (int i = 1; i <= cnt; i++) 5 System.out.printf(" "); 6 System.out.printf("\n"); 7 } 8... In this case, print() does not return a value. Zheng-Liang Lu Java Programming 174 / 207

51 Then one can reorganize main() like this: public static void main(string[] args) { System.out.printf("Total: %d\n", a + b + c + d + e); 5 print(100, 90, a); 6 print(89, 80, b); 7 print(79, 70, c); 8 print(69, 60, d); 9 print(59, 0, e); 10 } Be aware that this is not unique. Zheng-Liang Lu Java Programming 175 / 207

52 Exercise Write a program which prints a certain number of star lines determined by the user repeatedly until the input is negative. Input: n 0 A while loop which makes the program alive until n < 0 Allow the user to choose a symbol in addition to *? Zheng-Liang Lu Java Programming 176 / 207

53 static void printstar(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 } Scanner in = new Scanner(System.in); 3 int n; 4 String marker; 5 while (true) { 6 System.out.println("Enter a positive integer? "); 7 n = in.nextint(); 8 if (n < 0) break; 9 System.out.println("Choose a symbol? "); 10 marker = in.next(); 11 printstar(n, marker); 12 } 13 in.close(); 14 System.out.println("Bye."); Zheng-Liang Lu Java Programming 177 / 207

54 Invoking A Method Invoking a method executes the code in the method. When a program 7 calls a method, program control is transferred to the called method. Each time a method is invoked, the system creates an activation frame that stores parameters and variables for the method and places it in the call stack. A called method returns control to the caller when its return 8 statement is executed or when its end brace is reached. 7 Aka a callee. 8 In addition to break and continue is used as the exit point of methods and programs. Zheng-Liang Lu Java Programming 178 / 207

55 Note that the parameters are new declared variables within the method. When calling a method, you need to provide arguments, which must match the parameters in order, number, and compatible type, as defined in the method signature. This mechanism is so-called pass-by-value. Zheng-Liang Lu Java Programming 179 / 207

56 Zheng-Liang Lu Java Programming 180 / 207

57 Scope of Variables The scope of a variable is the part of the program where the variable can be referenced. A variable defined within a method is referred to as a local variable. For example, a parameter is actually a local variable. The scope of a method parameter covers the entire method. Moreover, you can declare a local variable with the same name in different blocks in a method Yet, you cannot declare a local variable twice in the same block or in nested blocks. Zheng-Liang Lu Java Programming 181 / 207

58 Example 1 public class incrementmain { 2 3 static int i = 1; // a local variable within this class 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", 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 182 / 207

59 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 183 / 207

60 Exercise Upgraded star printing Write a program which prints a certain number of lines with some symbol determined by the user repeatedly until the number of lines is negative. If the user enter -1, use * as the default symbol. Zheng-Liang Lu Java Programming 184 / 207

61 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 overloading. Zheng-Liang Lu Java Programming 185 / 207

62 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 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 186 / 207

63 Math Class The Math class contains the methods needed to perform basic mathematical functions. Note that the Math class is public and all methods within it are public and static. Two constants defined in Math class: Math.PI 9 and Math.E 10 Full document of Math class can be found here. Common methods are like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, random 9 π 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 187 / 207

64 Example Password generator Write a program which generate a random string as a password of ten characters. Note that there may be lower-case letters, upper-case letters, digital characters in the password. Recall that a character is coded using an integer. How to generate the feasible characters randomly? Zheng-Liang Lu Java Programming 188 / 207

65 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 189 / 207

66 public static void main (String[] args) { 3 System.out.println("Generating a password..."); 4 int key = 0; 5 for (int i = 1; i <= 10; ++i){ 6 key = (int)((math.random() 10) % 3); 7 switch (key) { 8 case 0: 9 System.out.printf("%s", getrandomuppercaseletter()); 10 break; 11 case 1: 12 System.out.printf("%s", getrandomlowercaseletter()); 13 break; 14 case 2: 15 System.out.printf("%s", getrandomdigitalcharacter()); 16 break; 17 } 18 } 19 } Zheng-Liang Lu Java Programming 190 / 207

67 Encapsulation The key to developing software is to apply the concept of abstraction. The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated 11 in the method and hidden from the client who invokes the method. If you decide to change the implementation, the client program will not be affected, provided that you do not change the method signature. For example, do you really know how System.out.println() works? 11 Encapsulation, inheritance, and polymorphism. Zheng-Liang Lu Java Programming 191 / 207

68 A Black Box Zheng-Liang Lu Java Programming 192 / 207

69 Divide and Conquer When developing a large program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose it 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 Do not write the entire program at once. Sitting in front of the computer is the last thing when programming. Zheng-Liang Lu Java Programming 193 / 207

70 Recursion 12 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. 12 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 194 / 207

71 Try Fractal. Zheng-Liang Lu Java Programming 195 / 207

72 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 196 / 207

73 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. 13 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? 13 Note that 0! = 1. Zheng-Liang Lu Java Programming 197 / 207

74 Zheng-Liang Lu Java Programming 198 / 207

75 Write a program which determines the first 10 factorials static int factorial(int n) { 3 if (n == 1) 4 return 1; 5 else 6 return n factorial(n 1); 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 199 / 207

76 Equivalence: Recursion Replaced by Loops for (int i = 1, j = 1; i <= 10; ++i) 3 System.out.println(i + "! = " + (j = i)); 4... In this case, the loop approach seems more compact than the recursive approach. One more intriguing question is, Can we always turn a recursive method into an iterative one? Yes, theoretically The Church-Turing thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 200 / 207

77 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. 15 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. 15 Stack overflow. Zheng-Liang Lu Java Programming 201 / 207

78 Zheng-Liang Lu Java Programming 202 / 207

79 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 203 / 207

80 The recursive implementation of fib is very simple and straightforward. Yet, it isn t efficient since it requires more time and memory fib is an exponential-time algorithm while factorial is a linear-time algorithm. (Why?) Zheng-Liang Lu Java Programming 204 / 207

81 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 } int f0 = 0, f1 = 1; 3 int tmp = 0; 4 for (int i = 0; i < 10; ++i){ 5 if (i == 0 i == 1) 6 System.out.println("F " + i + " = " + ((i == 1)? f1 : f0)); 7 else { 8 tmp = f0 + f1; 9 f0 = f1; 10 f1 = tmp; 11 System.out.println("F " + i + " = " + f1); 12 } 13 } Zheng-Liang Lu Java Programming 205 / 207

82 Problem Set Exercise 6.1 (Greatest common divisor) Write a program which receives two positive integers and returns the greatest common divisor using a recursive approach. Exercise 5.x (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 206 / 207

83 Zheng-Liang Lu Java Programming 207 / 207

1 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 / 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 information

Exercise. 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. 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 information

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. 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 information

Example. 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. 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 information

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Method 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 information

1 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 / 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 information

The return Statement

The 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 information

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Java 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 information

switch-case Statements

switch-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 information

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

1 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 information

Arithmetic Compound Assignment Operators

Arithmetic 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

1 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 // 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 information

Cloning 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, 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 information

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression. Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted

More information

Example: Monte Carlo Simulation 1

Example: 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 information

++x vs. x++ We will use these notations very often.

++x vs. x++ We will use these notations very often. ++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3

More information

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates

More information

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Logic is the anatomy of thought. John Locke ( ) This sentence is false. Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than

More information

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133 Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object

More information

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. Write a program which generates 2 random integers and asks the user to answer the math expression. Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then

More information

Recursion 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. 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 information

Jump 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. 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 information

Values in 2 s Complement

Values 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 information

Example. Password generator

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 information

Jump 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. 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 information

Arithmetic Compound Assignment Operators

Arithmetic 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 information

Example: Fibonacci Numbers

Example: 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 information

Exercise (Revisited)

Exercise (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 information

STUDENT LESSON A12 Iterations

STUDENT 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 information

Loops (while and for)

Loops (while and for) Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1 Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2 Motivation Name

More information

Scope 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. 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

IEEE Floating-Point Representation 1

IEEE Floating-Point Representation 1 IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either

More information

Nested Loops. A loop can be nested inside another loop.

Nested 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 information

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data 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 information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

Lecture 5: Methods CS2301

Lecture 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 information

Pace University. Fundamental Concepts of CS121 1

Pace 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 information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr 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 information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Selec%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 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 information

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8 CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

More information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-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 information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

1 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 / 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 information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

More information

Chapter 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 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 information

Selec%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 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 information

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a

More information

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Lecture #6-7 Methods

Lecture #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 information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Michele Van Dyne Museum 204B  CSCI 136: Fundamentals of Computer Science II, Spring Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1 Review of Java Basics Data Types Arrays NEW: multidimensional

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

CS115 Principles of Computer Science

CS115 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 information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review. 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

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

CS171:Introduction to Computer Science II

CS171:Introduction to Computer Science II CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 9/7/2012 1 Announcement Introductory/Eclipse Lab, Friday, Sep 7, 2-3pm (today) Hw1 to be assigned Monday,

More information

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition Statements Animated Version required for reproduction or display. Chapter 6-1 Objectives After you have read and studied this chapter, you should be able to Implement repetition control

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops Chapter 5: Loops and Iteration CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations Suppose that you need to print a string (e.g.,

More information

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Two 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 information

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 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 information

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017 Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method

More information

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

1 >> 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 information

Iteration statements - Loops

Iteration statements - Loops Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

More information

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

Programming Exercise 7: Static Methods

Programming Exercise 7: Static Methods Programming Exercise 7: Static Methods Due date for section 001: Monday, February 29 by 10 am Due date for section 002: Wednesday, March 2 by 10 am Purpose: Introduction to writing methods and code re-use.

More information

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of

More information

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Chapter 6 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 A Solution int sum = 0; for (int i = 1; i

More information

Functions. Systems Programming Concepts

Functions. 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 information

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 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 information

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

AP Programming - Chapter 6 Lecture

AP Programming - Chapter 6 Lecture page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Methods and Functions

Methods 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 information

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

34. 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 information

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Chapter 6 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 A Solution int sum = 0; for (int i = 1; i

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Chapter 6 Recursion. The Concept of Recursion

Chapter 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 information

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 4 Loops 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: So, how do

More information